C++学习笔记系列2-30
·
字符串追加
将字符串 A 的后面追加一个新的字符串 B 形成一个新的字符串,我们可以使用 append( )函数进行操作。
append( ) 函数和上一篇的 “+” 拼接基本一样,这两个都可以实现将字符串“合二为一”的功能。下面我们通过代码进行讲解。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = “hello”;
string str2 = “world”;
// 同样也是合成为:hello_world
// 我们使用上一篇的“+”进行 "_" 的拼接
// str1 = str1 + '_' ;
cout << "当前str1的内容为:" << str1 <<endl;
// 将 str2 追加到 str1 上
str1 . append( str2 );
cout << "当前str1的内容为:" << str1 <<endl;
}
输出:当前str1的内容为:hello_
当前str1的内容为:hello_world
通过以上代码,我们看到 append( ) 函数,需要使用str1通过 “.” 调用使用,然后在函数的参数列表中传入我们想追加的字符串变量名称,即:str2。看到结果和上一篇的拼接一模一样,这就是追加的用法。
更多推荐
所有评论(0)