C++中如何拼接字符串
时间: 2024-02-11 16:05:01 浏览: 59
在C++中,可以使用`+`符号或`+=`运算符来拼接字符串。例如:
```c++
std::string str1 = "Hello";
std::string str2 = "World";
std::string str3 = str1 + " " + str2;
std::cout << str3 << std::endl; // 输出:Hello World
std::string str4 = "Hello";
str4 += " ";
str4 += "World";
std::cout << str4 << std::endl; // 输出:Hello World
```
需要注意的是,使用`+`符号来拼接字符串时,要确保至少一个操作数是`std::string`类型,否则会出现编译错误。
相关问题
c++ printf 拼接字符串
C语言中,printf函数可以通过“%s”来输出字符串,而可以使用“%d”、“%f”等来输出其他类型的数据。如果要在输出的字符串中插入变量,可以使用sprintf函数,将字符串和变量放在一个字符串中。例如:
```
int num = 10;
char str[] = "apple";
char result[50];
sprintf(result, "The number is %d and the fruit is %s", num, str);
printf("%s", result);
// 输出:The number is 10 and the fruit is apple
```
c++string拼接字符串
在C++中,可以使用+运算符将两个字符串拼接在一起。例如:
```cpp
#include <iostream>
#include <string>
int main()
{
std::string str1 = "Hello, ";
std::string str2 = "world!";
std::string str3 = str1 + str2;
std::cout << str3 << std::endl;
return 0;
}
```
这段代码会输出 "Hello, world!"。除此之外,还可以使用append函数将一个字符串附加到另一个字符串的末尾。例如:
```cpp
#include <iostream>
#include <string>
int main()
{
std::string str1 = "Hello, ";
std::string str2 = "world!";
str1.append(str2);
std::cout << str1 << std::endl;
return 0;
}
```
这段代码也会输出 "Hello, world!"。需要注意的是,使用append函数时,被附加的字符串会被拼接到调用函数的字符串末尾。
阅读全文
相关推荐













