C++ string append方法的常用用法


append函數是向string的后面追加字符或字符串。
1).向string的后面加C-string
string s = “hello “; const char *c = “out here “;
s.append(c); // 把c類型字符串s連接到當前字符串結尾
s = “hello out here”;
2).向string的后面加C-string的一部分
string s=”hello “;const char *c = “out here “;
s.append(c,3); // 把c類型字符串s的前n個字符連接到當前字符串結尾
s = “hello out”;
3).向string的后面加string
string s1 = “hello “; string s2 = “wide “; string s3 = “world “;
s1.append(s2); s1 += s3; //把字符串s連接到當前字符串的結尾
s1 = “hello wide “; s1 = “hello wide world “;
4).向string的后面加string的一部分
string s1 = “hello “, s2 = “wide world “;
s1.append(s2, 5, 5); ////把字符串s2中從5開始的5個字符連接到當前字符串的結尾
s1 = “hello world”;
string str1 = “hello “, str2 = “wide world “;
str1.append(str2.begin()+5, str2.end()); //把s2的迭代器begin()+5和end()之間的部分連接到當前字符串的結尾
str1 = “hello world”;
5).向string后面加多個字符
string s1 = “hello “;
s1.append(4,’!’); //在當前字符串結尾添加4個字符!
s1 = “hello !!!!”;

C++ string append()添加文本

使用append()添加文本常用方法:

直接添加另一個完整的字符串:

如str1.append(str2);

添加另一個字符串的某一段子串:

如str1.append(str2, 11, 7);

添加幾個相同的字符:

如str1.append(5, '.');

注意,個數在前字符在后.上面的代碼意思為在str1后面添加5個".".


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM