C++:字符串的插入、删除和追加操作详解
一、字符串的插入(insert函数)
1)在字符串s1的第p(从0开始数)个位置前插入字符串s2:s1.insert(p, s2);
1 string s1 = "abcdef"; 2 string s2 = "ABC"; 3 s1.insert(2, s2); 4 cout << s1;

2)在字符串s1的第p个位置前插入字符串s2(取s2是从begin位置开始到end位置前的一个租房结束的子串):s1.insert(p, s2, begin, end);
1 string s1 = "abcdef"; 2 string s2 = "ABC"; 3 s1.insert(2, s2, 0, 2); 4 cout << s1;
![]()
3)在字符串s1的第p个位置前插入n个字符c:s1.insert(p, n, c);
1 string s1 = "abcdef"; 2 char c = 'A'; 3 s1.insert(2, 2, c); 4 cout << s1;
![]()
二、字符串的删除操作(erase函数)
1)删除字符串s1从第p个位置开始之后所有的字符(包括第p个字符):s1.erase(p);
1 string s1 = "abcdef"; 2 s1.erase(3); 3 cout << s1;
![]()
2)删除字符串s1从第p个位置开始的前n个字符:s1.erase(p, n);
1 string s1 = "abcdef"; 2 s1.erase(3, 2); 3 cout << s1;

三、字符串的追加操作(append函数)
1)在字符串s1后面追加字符串s2:s1.append(s2);
1 string s1 = "abcdef"; 2 string s2 = "gh"; 3 s1.append(s2); 4 cout << s1;

2)在字符串s1后面追加具体字符串(即不能定义,直接写,如“1234”)的前n个字符:s1.append(“1234”, n);
1 string s1 = "abcdef"; 2 s1.append("1234", 2); 3 cout << s1;

PS:s1.append(s2, 2) 这种写法是错误的
3)在字符串s1后面追加n个重复的字符:s1.append(n, ' c');
1 string s1 = "abcdef"; 2 s1.append(3, 'A'); 3 cout << s1;

                    
                
                
            
        
浙公网安备 33010602011771号