溫馨提示×

c++拼接字符串的方式有哪些

c++
小億
100
2024-03-29 16:17:08
欄目: 編程語言

在C++中,拼接字符串的方式有以下幾種:

  1. 使用"+"運(yùn)算符
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2; // result為"Hello World"
  1. 使用append()函數(shù)
std::string str1 = "Hello";
std::string str2 = "World";
str1.append(" ").append(str2); // str1為"Hello World"
  1. 使用stringstream
std::string str1 = "Hello";
std::string str2 = "World";
std::stringstream ss;
ss << str1 << " " << str2;
std::string result = ss.str(); // result為"Hello World"
  1. 使用std::ostringstream
std::string str1 = "Hello";
std::string str2 = "World";
std::ostringstream oss;
oss << str1 << " " << str2;
std::string result = oss.str(); // result為"Hello World"

這些是一些常用的拼接字符串的方式,根據(jù)具體情況選擇合適的方式。

0