乐闻世界logo
搜索文章和话题

How to concatenate two strings in C++?

4 个月前提问
3 个月前修改
浏览次数23

1个答案

1

在C++中连接两个字符串有多种方法,常见的包括使用+运算符和使用append()函数。我会逐一介绍这两种方法,并给出示例。

使用 + 运算符

在C++中,可以直接使用+运算符来连接两个std::string类型的字符串。这种方法简单直观,适用于连接少量的字符串。

示例代码:

cpp
#include <iostream> #include <string> int main() { std::string str1 = "Hello, "; std::string str2 = "World!"; std::string result = str1 + str2; std::cout << result << std::endl; // 输出: Hello, World! return 0; }

使用 append() 函数

另一种方法是使用std::string类的append()成员函数。这种方法非常适合在已有字符串的基础上连续添加多个字符串,且效率通常比使用+运算符要高,特别是在处理大量数据时。

示例代码:

cpp
#include <iostream> #include <string> int main() { std::string str1 = "Hello, "; std::string str2 = "World!"; str1.append(str2); std::cout << str1 << std::endl; // 输出: Hello, World! return 0; }

总结

对于简单的字符串连接,+运算符是一个快速且直观的选择。但如果涉及到大量字符串的连续拼接,建议使用append()方法,因为它可以减少内存的重新分配次数,从而提高效率。在实际开发中,选择哪种方法应根据具体场景和性能需求来定。

2024年6月29日 12:07 回复

你的答案