Basic usage of string in C++
Article directory
1. Initialization
-
There are two main ways to initialize, one is to use the equal sign for copy initialization, and the other is to directly initialize without using the equal sign.
-
string str1; //生成空字符串 string str2("123456789"); //生成"1234456789"的复制品 string str3("12345", 0, 3);//结果为"123" string str4("0123456", 5); //结果为"01234" string str5(5, '1'); //结果为"11111" string str6(str2, 2); //结果为"3456789"
2. Insert
string str = "123456789";
//在字符串str的数组下标为6的位置上面插入2个字符x
str.insert(6,2,'x'); //结果为str:123456xx789
string str1("x");
str.insert(6,str1); //结果为str:123456x789
string str10 = "1234589";
string str11 = "67";
//在str的数组下标为5的位置插入 str11从0位置开始的2个数
str10.insert(5,str11,0,2);//结果为str10:123456789
str10.insert(5,str11,2);//表示插入str11开始的两个数
-
Note: If you directly use the following code to insert, an error will be reported and an error will be prompted.
error: invalid conversion from 'char' to 'const char ' *, needs to be defined as const type.
str.insert(6,'x');
3. Replacement
-
Replacement is similar to insertion
-
string str = "123456789"; string str12 = "321"; //删除str从0开始的三个数,然后插入str12从0开始的三个数 str.replace(0,3,str12,0,3);//结果为str:321456789 //删除str从0开始的三个数,然后插入str12 str.replace(0,3,str12);//结果为str:321456789
4. Add
-
To add, use the keyword append or directly use '+' connection.
string str = "123456789"; string str12 = "321"; str.append(str12,0,3);//str:123456789321
5. Assignment
//s.assign(n,ch) 将n个ch字符赋值给字符串s
//s.assign(str,pos,n) 将字符串str从pos开始的n个字符赋值给字符串s
6. Delete
string str = "123456789";
str.erase(8,1);//结果为str:12345678
7. Exchange
string str10 = "1234589";
string str11 = "67";
swap(str10,str11);//str10:67 str11:1234589
swap(str11[0],str11[1]);//str11:76
8. Reversal
string str = "abcdefghijklmn";
reverse(str.begin(),str.end()); // str = "nmlkjihgfedcba"
9. Search
- rfind is to find the position of the last occurrence (opposite of find).
string str20 = "123456789";
string key = "2";
//s.find(str) 查找字符串str在当前字符串s中第一次出现的位置
int pos1 = str20.find(key); //pos1:1 ,未查找到返回-1
//从3位置开始查找
int pos1 = str20.find(key,3); //pos1:-1,未查找到返回-1
-
find_xxx_of function
-
string str = "The early birds catch the warm"; //长度30 string key = "aeiou";
// s.find_first_of(str) 查找字符串str中的任意字符在当前字符串s中第一次出现的位置 int pos1 = str.find_first_of(key); C // 2 //s.find_first_of(str,pos) 查找字符串str中的任意字符在当前字符串s的[pos,end]中第一次出现的位置 int pos2 = str.find_first_of(key, 10); // 11 //s.find_first_of(cstr,pos,n) 查找字符串str前n个任意字符在当前字符串s的[pos,end]中第一次出现的位置 //此处不可将"aeiou"替换为key int pos3 = str.find_first_of("aeiou", 7, 2); // 17 //s.find_first_of(ch,pos) 查找字符ch在当前字符串s的[pos,end]中第一次出现的位置 int pos4 = str.find_first_of('r', 0); // 6