反转字符串为常见的日常操作,在c++中可以用algorithm里的reverse方法进行操作。
#include#include #include #include using namespace std; void func0() { string s = "abcde"; std::reverse(s.begin(), s.end()); cout<<"s is: "< 上述方法输出为
s is: edcba s1 is: abcde s2 is: edcba使用reverse方法以后,字符串本身发生了改变。如果需要保留原有字符串,则可以再新创建一个字符串进行反转。
2.插入字符插入字符可以使用push_back与insert方法。其中,push_back是在字符串尾部操作,而insert可以在字符串任意位置进行操作。
void func1() { string s = "abcde"; s.push_back('f'); s.insert(s.begin(), '0'); cout<<"s is: "<s is: 0abcdef3.字符串拼接append方法可以用来进行字符串拼接,”+“也可以收到同样效果
void func2() { string s = "aaa"; s.append("bbb"); cout<<"s is: "<s is: aaabbb ss is: aaabcd4.字符串遍历遍历可以使用下标,也可以使用迭代器。迭代器可以是正向,也可以是反向。
void func3() { string s = "abcd"; for(int i=0; i a b c d a b c d d c b a5.删除字符串中的字符void func4() { string s = "abcdefghigk"; s.erase(s.begin()); cout<bcdefghigk efghigk从上面的例子可以看出,erase方法中的参数,可以使用迭代器,也可以指定索引位置。
6.字符串替换void func5() { string s = "ni hao hello world"; s.replace(0, 2, "ta"); cout<ta hao hello world7.删除所有空格void func6() { string str = "ni hao aaa"; str.erase(std::remove(str.begin(), str.end(), ' '), str.end()); cout< nihaoaaa 8注意remove方法与erase方法配合使用。
8.转大小写void func7() { string s = "abcd"; for(int i=0; i s is: ABCD s is: abcd9.判断子串起始位置void func8() { string s = "abcdefg"; int index1 = s.find("abc"); cout<<"index1 is: "< index1 is: 0 index2 is: -1find方法如果找到子串,返回起始位置。如果没有找到,则返回-1.
10 获取子串void func9() { string s = "abcdefg"; cout< abc注意substr方法,得到的结果为左闭右开区间。



