本篇介绍字符串的拼接

字符串拼接就是将两个字符串合并为一个字符串,如下:

string str1 = “AAA”;

string str2 = “BBB”;

合成为一个:AAABBB,这样的字符串

 

合并的符号:+、+=

具体操作如下:

#include <iostream>

#include <string>

using namespace std;

int main()

{        

        string str1 = “hello”;

        string str2 = “world”;

        // 我们想合成一个“hello_world”这样一个新字符串,首先先为 str1 后面添加一个 “_”

        str1 = str1 + '_';

        cout << "当前str1的内容为:" << str1 <<endl;

        str1 += str2; // 将 world 通过 += 再次赋值给 str1

        cout << "当前str1的内容为:" << str1 <<endl;

}

输出:当前str1的内容为:hello_

           当前str1的内容为:hello_world

 

以上是字符串的拼接方式,我们可以通过 “+” 进行两个字符串的拼接,通过 “+” 合成为一个新的字符串,但是需要注意的是字符串的拼接顺序,A、B 两个字符串,如果想将 B 拼接到 A,那么就要采用“A += B”,反之就是“B += A”。这是通过运算符进行拼接。

 

更多推荐