C/C++ 字串連接的3種方法

本篇 ShengYu 介紹 C/C++ 字串連接的3種方法,寫程式中字串連接是基本功夫,而且也蠻常會用到的,所以這邊紀錄我曾經用過與所知道的字串連接的幾種方式,
以下為 C/C++ 字串連接的內容章節,

  • C 語言的 strcat
  • C++ string 的 append()
  • C++ string 的 += operator

那我們就開始吧!

C 語言的 strcat

C 語言要連接 c-style 字串通常會使用 strcat,要使用 strcat 的話需要引入的標頭檔 <string.h>
strcat 函式原型為

1
char * strcat(char * destination, const char * source);

strcat() 會將 source 字串連接在 destination 字串後,來看看下面的 strcat 用法範例吧!

cpp-string-append.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// g++ cpp-string-append.cpp -o a.out
#include <stdio.h>
#include <string.h>
using namespace std;

int main() {
const char *str1 = "hello";
const char *str2 = "world";
char dest[64] = {0};

strcat(dest, str1);
strcat(dest, " ");
strcat(dest, str2);
printf("dest: %s\n", dest);

return 0;
}

結果如下,

1
dest: hello world

如果是使用 std::string 的話,在字串連接上就有一些方便的成員函式可以使用,以下介紹 C++ std::string 字串連接的兩種方式,

C++ string 的 append()

這邊介紹 C++ string 的 append(),std::string 使用 append() 可以連接 std::string 以外也可以連接 c-style 字串,

cpp-string-append2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// g++ cpp-string-append2.cpp -o a.out
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "hello";
string str2("world");
string str3;

str3.append(str1);
str3.append(" ");
str3.append(str2);

cout << str3 << "\n";

return 0;
}

結果如下,

1
hello world

另外 C++ string 還可以一直使用 append() 串接下去,寫法像這樣,

cpp-string-append3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// g++ cpp-string-append3.cpp -o a.out
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "hello";
string str2("world");
string str3;

str3.append(str1).append(" ").append(str2);

cout << str3 << "\n";

return 0;
}

C++ string 的 += operator

最後要介紹的是 C++ string 的 += operator,也是最直覺的一種 C++ 字串連接寫法,直接用 += 來連接兩字串,也可以連接 c-style 字串,

cpp-string-append4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// g++ cpp-string-append4.cpp -o a.out
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "hello";
string str2("world");
string str3;

str3 += str1;
str3 += " ";
str3 += str2;

cout << str3 << "\n";

return 0;
}

結果如下,

1
hello world

其它相關文章推薦
如果你想學習 C++ 相關技術,可以參考看看下面的文章,
C/C++ 新手入門教學懶人包
C/C++ 字串比較的3種方法
C/C++ 字串搜尋的3種方法
C/C++ 字串分割的3種方法