溫馨提示×

c++字符串拼接的方法是什么

c++
小億
128
2023-11-21 00:50:05
欄目: 編程語言

在C++中,字符串拼接有多種方法,包括使用+運算符、使用+=運算符、使用字符串拼接函數等等。

  1. 使用+運算符:

    std::string str1 = "Hello";
    std::string str2 = "World";
    std::string result = str1 + " " + str2; // 字符串拼接
    
  2. 使用+=運算符:

    std::string str1 = "Hello";
    std::string str2 = "World";
    str1 += " " + str2; // 將str2拼接到str1后面
    
  3. 使用字符串拼接函數:

    • 使用strcat函數:
      char str1[100] = "Hello";
      char str2[] = "World";
      strcat(str1, " ");
      strcat(str1, str2); // 字符串拼接
      
    • 使用stringstream類:
      #include <sstream>
      std::string str1 = "Hello";
      std::string str2 = "World";
      std::stringstream ss;
      ss << str1 << " " << str2; // 字符串拼接
      std::string result = ss.str();
      

需要注意的是,使用字符串拼接函數時,需要確保目標字符串的長度足夠長,以避免緩沖區溢出的問題。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女