string 字符串连接

来源:互联网 发布:碎屏幕手机壁纸软件 编辑:程序博客网 时间:2024/05/22 14:14

有了 string 类,我们可以使用”+“或”+=“运算符来直接拼接字符串,非常方便,再也不需要使用C语言中的strcat()strcpy()malloc()等函数来拼接字符串了,再也不用担心空间不够会溢出了。

+“来拼接字符串时,运算符的两边可以都是string 字符串,也可以是一个string 字符串和一个C风格的字符串,还可以是一个string 字符串和一个char 字符。

请看下面的例子:

#include <iostream>

#include <string>

using namespace std;

int main(){

    string s1, s2, s3;

    s1 = "first";

    s2 = "second";

    s3 = s1 + s2;

    cout<< s3 <<endl;

    s2 += s1;

    cout<< s2 <<endl;

    s1 += "third";

    cout<< s1 <<endl;

    s1 += 'a';

    cout<< s1 <<endl;

    return 0;

}

运行结果:

firstsecond

secondfirst

firstthird

firstthirda

还有一种就是使用append函数

例如string a = “123”;

string b = “456”;

a.append(b);//132456

原创粉丝点击