1. 提取
函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数时需要提取的子字符串的长度。
函数原型为:string substr (size_t pos = 0, size_t len = nops) const;
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a1 = "first second third";
string a2;
string a3;
string a4;
a2 = a1.substr(6, 6); //从a1的第6个字符开始提取,提取六个
a3 = a1.substr(3, 5); //我要尝试一下,中间有空格会怎么样
a4 = a1.substr(0, 7);
cout << a1 << "\n";
cout << a2 << "\n";
cout << a3 << "\n";
cout << a4 << "\n";
return 0;
}
程序运行结果为:
first second third
second
st se
first s
总结:这里的第一个参数可以简单的理解为前多少个不提取,第二个参数就是提取的数量,空格也计算。
2. 比较
"=="、"!="、"<="、">="、"<"和">"操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a1 = "seconda";
string a2 = "secondthird";
string a3 = "secondx";
string a4 = "secontthird1";
if (a1 == a2)
{
cout << "a1 == a2" << endl;
}
if (a1 != a2)
{
cout << "a1 != a2" << endl;
}
if (a1 < a2)
{
cout << "a1 < a2" << endl;
}
if (a1 > a2)
{
cout << "a1 > a2" << endl;
}
if (a2 < a3)
{
cout << "a2 < a3" << endl;
}
if (a2 > a3)
{
cout << "a2 > a3" << endl;
}
if (a2 < a4)
{
cout << "a2 < a4" << endl;
}
if (a2 > a4)
{
cout << "a2 > a4" << endl;
}
return 0;
}
程序运行结果为:
a1 != a2
a1 < a2
a2 < a3
a2 < a4
总结:比较规则就是先从左到右比较,前面相同的话就从第一个不相同的比较,知道出现第一个不同的,这时排在前面的就要小,例如a1中的a小于a2中的t,所以输出a1 < a2;同理,大的就大于,也就是a2和a3;如果前面都一样,例如a2和a4,a4的长度大于a2,所以a4 > a2。
3. 添加
insert()函数(erase可以用于删除,都一样)可以在string字符串中的指定的位置插入另一个字符串,它的原型为:
string& insert (size_t pos, const string& str);
pos表示要插入的下标,str表示要插入的字符串,它可以是string变量,也可以是C风格的字符串。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1, s2, s3;
s1 = s2 = "1234567890";
s3 = "aaa";
s1.insert(5, s3);
cout << s1 << endl;
s2.insert(5, "bbb");
cout << s2 << endl;
return 0;
}
程序运行结果:
12345aaa67890
12345bbb67890
注意:insert()函数的第一个参数有越界的可能,如果越界,则会产生运行时异常。
4. 搜索也就是匹配
函数find_first_of()和find_last_of()执行简单的模式匹配
例如在字符串中查找单个字符c
函数find_first_of()查找在字符串中第一个出现的字符c,而函数find_last_of()查找最后一个出现的c。匹配的位置是返回值,如果没有匹配发生,则函数返回-1
int find_first_of(char c, int start = 0):查找字符串中第一个出现的c,由位置start开始。如果有匹配,则返回匹配位置;否则返回-1,默认情况下start为0,函数搜索整个字符串
int last_first_of(char c):查找字符串中最后一个出现的c。有匹配,则返回匹配位置;否则返回-1。该搜索在字符串末尾查找匹配,所以没有提供起始位置。
示例:
string str = "Mississippi";
int index;
// 's ' 在index 为 2、3、5、6处出现
index = str.find_first_of('s',0); // index为 2
index = str.find_first_of('s',4); // index为 5
index = str.find_first_of('s',7); // index为 -1
// ‘s’的最后出现在 index= 6
index = str.find_last_of('s');
// while 循环输出每个'i'的index
while((index = str.find_first_of('i', index))!= -1)
{
cout << "index" << index << " ";
index++; // restart search at next indx
}