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

How to concatenate two strings in C++?

1个答案

1

There are multiple ways to concatenate two strings in C++. Common methods include using the + operator and the append() function. I will introduce both methods step by step, along with examples.

Using the + Operator

In C++, you can directly use the + operator to concatenate two std::string objects. This method is simple and intuitive, suitable for concatenating a small number of strings.

Example Code:

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; // Output: Hello, World! return 0; }

Using the append() Function

Another method is to use the append() member function of the std::string class. This method is particularly suitable for appending multiple strings to an existing string, and it is generally more efficient than using the + operator, especially when handling large amounts of data.

Example Code:

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

Summary

For simple string concatenation, the + operator is a quick and intuitive choice. However, when dealing with continuous concatenation of many strings, it is recommended to use the append() method, as it reduces the number of memory reallocations, thereby improving efficiency. In actual development, the choice of method should be based on specific scenarios and performance requirements.

2024年6月29日 12:07 回复

你的答案