[微信公众号:Cpp入门到精通]有完整六十六节知识,STL知识总结,欢迎关注学习!!
上一节我们介绍了string容器的初始化和一些基本操作。这节我们继续来学习string容器的其他操作。
首先我们要介绍的是string容器的字符串操作:
1.使用 find() 函数查找子串。
rfind()为从右往左查:
string s1;
s1.assign("Hello C++");
cout << "s1=" << s1 << endl;
cout << "字符串中第一次出现l的位置下标为:" << s1.find("l") << endl;
cout << "从右往左查为:" << s1.rfind("l") << endl;//这个l为第二个l,下标为3
结果如下:
s1=Hello C++
字符串中第一次出现l的位置下标为:2
从右往左查为:3
2.使用 replace() 函数替换子串。
string s1;
s1.assign("Hello C++");
cout << "s1=" << s1 << endl;
string s2 = { "Welcome" };
cout << "s2=" << s2 << endl;
s1.replace(3, 5, s2);
cout << "s1=" << s1 << endl;
replace(3, 5, s2) 将从位置 3 开始(包括位置 3),替换长度为 5 的子串("lo C+")为给定的字符串 "Welcome"。最终输出将是 "HelWelcome+"。
s1=Hello C++
s2=Welcome
s1=HelWelcome+
3.使用 erase() 函数删除子串。
string s1;
s1.assign("Hello C++");
cout << "s1=" << s1 << endl;
s1.erase(1, 4);
cout << "s1=" << s1 << endl;
s1.erase(1,4)表示删除s1中从下标1开始4个字符大小的字符串:
s1=Hello C++
s1=H C++
4.使用 insert() 函数插入子串。
string s1;
s1.assign("Hello C++");
cout << "s1=" << s1 << endl;
s1.insert(1, "666");
cout << "s1=" << s1 << endl;
s1.insert(1,"666")表示在s1下标1处插入字符串“666”:
s1=Hello C++
s1=H666ello C++
5.使用 substr() 函数获取子串。
string s1;
s1.assign("Hello C++");
cout << "s1=" << s1 << endl;
cout << s1.substr(2, 6) << endl;
substr(2, 6) 将返回主字符串中从位置2开始,长度为6的子串,即 "llo C+"。substr函数的第一个参数不可省略,表示的是子串起始位置,第二个参数可以指定,不指定默认为字符串尾:
s1=Hello C++
llo C+
我们可以进行两个字符串的比较操作,字符串的比较通常是通过字符的字典序(按照 ASCII编码顺序)来进行的:
1.使用比较运算符:
==:判断两个字符串是否相等。
!=:判断两个字符串是否不相等。
<、<=、>、>=:按字典序比较两个字符串的大小。
string s1 = "Hello";
string s2 = "C++";
if (s1 == s2) {
cout << "s1=s2" << endl;
}
else if (s1 < s2) {
cout << "s1<s2" << endl;
}
else
{
cout << "s1>s2" << endl;
}
结果如下:
s1>s2
2.使用 compare() 函数:
compare() 函数返回一个整数,表示两个字符串的比较结果。
如果返回值为 0,则表示两个字符串相等。
如果返回值小于 0,则表示调用字符串小于参数字符串。
如果返回值大于 0,则表示调用字符串大于参数字符串。
string s1 = "Hello";
string s2 = "C++";
int m=s1.compare(s2);
if (m == 0) {
cout << "s1=s2" << endl;
}
else if (m < 0) {
cout << "s1<s2" << endl;
}
else {
cout << "s1>S2" << endl;
}
结果如下:
s1>S2
string容器的相关操作的讲解到此结束,感谢观看!欢迎各位的点赞与关注!您的点赞和关注是我学习更新的动力!