1.append(追加字符串)
#include<iostream>
using namespace std;
int main()
{
string s1 = "hello";
s1.append(" world!"); //将" world!"添加到s1.
cout << s1 << endl;
string s2 = "hello";
s2.append("hello world!", 5, 3); //将"hello world!"从下标5开始(即空格' ')的三个字符添加到s2.
cout << s2 << endl; //注意上面注释中提到的下标从0开始
string s3 = "hello";
s3.append(" world!", 4); //将" world!"中前4个字符添加到s3.
cout << s3 << endl;
string s4 = "hello"; //将3个'!'添加到s4
s4.append(3, '!');
cout << s4 << endl;
return 0;
}
2.assign(为字符串赋值)
#include<iostream>
using namespace std;
int main()
{
string s1 = "hello";
s1.assign("world!"); //给s1赋值"world!"
cout << s1 << endl;
string s2 = "hello";
s2.assign("world!", 1, 3); //将"world!"从下标1开始(即'o')的三个字符赋值给s2,赋值后应为"orl".
cout << s2 << endl; //注意上面注释中提到的下标从0开始
string s3 = "hello";
s3.assign("world!", 4); //将"world!"中前4个字符赋值给s3,结果应为"worl".
cout << s3 << endl;
string s4 = "hello"; //将3个'!'赋值给s4,赋值后应为"!!!".
s4.assign(3, '!');
cout << s4 << endl;
return 0;
}
3. at clear erase empty
(1) at(index): 返回当前字符串中index位置的字符
(2) clear(): 清空字符串
(3) erase(index, n): 删除字符串从index开始的n个字符
(4) empty(): 检测字符串是否为空
#include<iostream>
using namespace std;
int main()
{
string s = "hello world!";
cout << s.at(4) << endl; //s的下标为4的字符为'o',故应输出'o'.
cout << s.erase(2, 5) << endl; //将s从下标2开始的5个字符删去,结果应该为"heorld!"
s.clear(); //将字符串s清空。
cout << s.empty() << endl; //判断s是否为空,为空,所以应输出1,否则输出0.
return 0;
}
4. compare(比较字符串)
#include<iostream>
using namespace std;
int main()
{
string s1{ "hello" }; //初始化列表
string s2{ "hfllo" };
//compare就是实现ascii码相减
cout << s1.compare(s2) << endl; //下标1不相等,'e'-'f'=-1,故输出结果应为-1。
cout << s2.compare(s1) << endl; //输出结果应该为1。
cout << s1.compare("hello") << endl; //两个字符串相等,输出结果应该为0.
return 0;
}
5. substr(获取字串)
#include<iostream>
using namespace std;
int main()
{
string s1 = "hello";
cout << s1.substr(1, 3) << endl; //获取从下标1开始长度为3的子串,故输出应为"ell".
cout << s1.substr(3) << endl; //获取从下标3直到末尾的子串,故输出为"lo".注意与append、assign
return 0; //从前面开始的区别
}
6. find(搜索字符串)
#include<iostream>
using namespace std;
int main()
{
string s1 = "hello";
//find可以实现对字符或字符串的搜索
cout << s1.find("el") << endl; //"el"从下标1开始,输出1
cout << s1.find("el", 2) << endl; //从下标2开始不能找到"el",返回nops(一个特别的标记).
cout << s1.find('l') << endl; //'l'的下标为2,故输出2
cout << s1.find('l', 3) << endl; //从下标3开始找到'l'的下标为3,故输出3.
return 0;
}
7. insert replace(插入和替换字符串)
#include<iostream>
using namespace std;
int main()
{
string s1 = "hello world!";
cout << s1.insert(6, "beautiful ") << endl;//将"beautiful "插入到s1中下标为6的地方,即"hello beautiful world!".
string s2 = { "hello" };
cout << s2.insert(1, 3, '!') << endl; //将3个'!'插入到s2的下标1处。
string s3 = { "hello jave" };
cout << s3.replace(6, 4, "C++") << endl; //将s3从下标6开始的4个字符用"C++"替换,应输出"hello C++".
return 0;
}