C++学习 --string

目录

1, 什么是string

2, 创建string

3, 操作string

3-1, 赋值

3-1-1, 赋值(=)

3-1-1, 赋值(assign)

3-2, 修改

3-2-1, 拼接

3-2-1-1, 拼接(+)

3-2-1-2, 拼接(append)

3-2-2, 替换(replace)

3-2-3, 单字符操作

 3-2-4, 插入(insert)

3-3, 查询

3-3-1, 查找(find)

3-3-2, 查找(rfind)

 3-3-3, 子串(substr)

 3-3-4, 单字符操作

3-3-5, 获取首尾字符

3-4, 比较(compare)

3-5, 删除(erase)

3-6,获取字符串长度


1, 什么是string

C++中的字符串, 本质是一个类

2, 创建string

通过string 对象名, 创建一个string

//普通创建
string str1;
//拷贝构造,str1拷贝给str2
string str2(str1);
//定义5个a组成的字符串
string str3(5, 'a');

3, 操作string

3-1, 赋值

3-1-1, 赋值(=)

通过string 对象名 = 字符串, 进行string对象赋值

//创建str1, 并赋值aaa
string str1 = "aaa";
//创建str2, 并赋值bbb
string str2("bbb");

3-1-1, 赋值(assign)

通过对象名.assign(字符串), 进行string对象赋值

string str2;
str2.assign("bbb");
//字符串有5个字符c组成
string str3;
str3.assign(5,  'c');
//将str3拷贝给str4
string str4;
str4.assign(str3);
//表示获取str1从第3个索引开始直到最后的字符赋值给str2
str2.assign(str1, 3);
//表示获取str1从第3个索引开始的后两个字符赋值给str2
str2.assign(str1, 3, 2);

3-2, 修改

3-2-1, 拼接

3-2-1-1, 拼接(+)

通过对象1+对象2, 拼接两个字符串

string str1 = "hello c++";
//注意拼接之间没有空格, 等价于str1 += str1
str1 = str1 + str1;
3-2-1-2, 拼接(append)

通过对象名1.append(对象名2), 拼接两个字符串

string str1 = "hello c++";
str1.append(str1);
//表示从str1的第3个索引开始直到最后, 拼接到str1后面
str1.append(str1, 3);
//表示从str1的第2个索引开始, 拼接3个字符到str1后面
str1.append(str1, 2, 3);

3-2-2, 替换(replace)

 通过对象名.replace(起始索引, 结束索引, 替换值), 可替换字符串内容

string str1 = "hello c++";
//将第1~3号位索引对应的信息替换为aaa
str1.replace(1, 3, "aaa");

3-2-3, 单字符操作

通过对象名[索引]或者对象名.at(索引), 获取字符串的单个字符

//获取索引为1对应的字符
cout << str1[1] << endl;
cout << str1.at(1) << endl;

 3-2-4, 插入(insert)

通过对象名.insert(索引, 值), 向字符串中插入数据

//在str1的第二个索引位置插入aaa
str1.insert(2, "aaa");

3-3, 查询

3-3-1, 查找(find)

通过对象名.find(), 可查找字符串中的子串, 从开始查找, 返回对应的首次匹配索引

cout << str1.find("aa") << endl;

3-3-2, 查找(rfind)

通过对象名.rfind(), 可查找字符串中的子串, 从开始查找, 返回对应的首次匹配索引

cout << str1.find("l") << endl;

 3-3-3, 子串(substr)

通过对象名.substr(起始索引, 结束索引), 返回起始索引~结束索引的字符

//返回str1的第1~4个字符
cout << str1.substr(1, 4) << endl;

 3-3-4, 单字符操作

通过对象名[索引]或者对象名.at(索引), 修改字符串的单个字符

//修改索引为1对应的字符
str1[1] = 'a';
str1.at(2) = 'a';
cout << str1[1] << endl;
cout << str1.at(1) << endl;

3-3-5, 获取首尾字符

通过对象名.front(), 获取字符串首字符, 通过对象名.back(), 获取字符串尾字符

cout << str1.front() << endl;
cout << str1.back() << endl;

3-4, 比较(compare)

通过对象名1.compare(对象名2), 进行比较字符串大小逐个比较两个字符串的Ascii码, 相等返回0, 对象名1大于对象名2返回1, 对象名1小于对象名2返回-1 

string str1 = "hello c++";
string str2 = "1hello c++";
cout << str1.compare(str2) << endl;

3-5, 删除(erase)

通过对象名.erase(起始索引, 结束索引), 删除字符串中指定的字符

//删除str1的第1~3个字符
str1.erase(1, 3);
cout << str1 << endl;

3-6,获取字符串长度

cout << str1.size() << endl;

你可能感兴趣的:(C++,学习)