c++string函数(二)——常用方法(reverse,insert等……)
·
一、string中加字符串
1.1 直接使用字符串"+"相加
string a = "123";
string b = "456";
a += b;
结果:
123456
1.2 使用insert函数
string1.insert(index, string2);:在index位置插入字符串string
(返回值需要用一个字符串来接收)
int index = 2;
string s = "strings";
string temp = "'luanru'";
temp = s.insert(index, temp);
cout << temp << endl;
结果:
str'luanru'ings
二、字符串反转reverse
reverse( string.begin(), string.end() );在原地反转字符串
temp = "nihao";
reverse(temp.begin(), temp.end());
cout << temp << endl;
结果:
oahin
三、截取字符串
3.1 substr
s.substr(index, len):返回一个string,包含字符串s中从index开始的len个字符的拷贝
tip:
- p的默认值是0,n的默认值是s.size() - p,即不加参数会默认拷贝整个s
- 返回值需要用一个字符串来接收
int index = 0;
int len = 2;
string s = "abccc";
string temp;
temp = s.substr(index, len); //s.substr(0, 2)截取字符串0~2位置的子串
cout << temp << endl;
结果:
ab
更多推荐
所有评论(0)