跳转到内容

C++ 字符串连接

来自代码酷

模板:Note

C++字符串连接[编辑 | 编辑源代码]

字符串连接是编程中常见的操作,指将两个或多个字符串按顺序合并为一个新字符串的过程。在C++中,可以通过多种方式实现字符串连接,包括使用运算符、成员函数或标准库函数。

基本方法[编辑 | 编辑源代码]

使用 + 运算符[编辑 | 编辑源代码]

C++中的std::string类重载了+运算符,可以直接用于连接字符串:

#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;
}

模板:Note

使用 append() 成员函数[编辑 | 编辑源代码]

std::stringappend()成员函数可以追加内容到现有字符串:

#include <iostream>
#include <string>

int main() {
    std::string str = "Learning ";
    str.append("C++");  // 追加C风格字符串
    
    std::cout << str << std::endl;  // 输出: Learning C++
    return 0;
}

高级方法[编辑 | 编辑源代码]

使用 operator+=[编辑 | 编辑源代码]

+=运算符是最高效的原地连接方式,避免创建临时对象:

#include <iostream>
#include <string>

int main() {
    std::string str = "The answer is ";
    str += 42;  // 自动转换并追加
    
    std::cout << str << std::endl;  // 输出: The answer is 42
    return 0;
}

使用 std::stringstream[编辑 | 编辑源代码]

对于需要混合连接多种类型或大量字符串时,std::stringstream更高效:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    ss << "PI: " << 3.14159 << " is irrational";
    
    std::string result = ss.str();
    std::cout << result << std::endl;  // 输出: PI: 3.14159 is irrational
    return 0;
}

性能比较[编辑 | 编辑源代码]

不同连接方法的性能差异(假设连接N次):

barChart title 字符串连接方法性能比较 x-axis 方法 y-axis 时间复杂度 bar "+ operator" : O(N²) bar "append()" : O(N) bar "+=" : O(N) bar "stringstream" : O(N)

页面模块:Message box/ambox.css没有内容。

实际应用案例[编辑 | 编辑源代码]

日志系统构建[编辑 | 编辑源代码]

在日志系统中,需要动态构建包含时间戳和消息的字符串:

#include <chrono>
#include <iomanip>
#include <sstream>
#include <string>

std::string createLogEntry(const std::string& message) {
    auto now = std::chrono::system_clock::now();
    auto time = std::chrono::system_clock::to_time_t(now);
    
    std::stringstream ss;
    ss << "[" << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S") << "] " << message;
    return ss.str();
}

SQL查询构造[编辑 | 编辑源代码]

构建动态SQL查询时(注意:实际应用应使用参数化查询防止SQL注入):

std::string buildQuery(const std::string& table, const std::vector<std::string>& columns) {
    std::string query = "SELECT ";
    
    for (size_t i = 0; i < columns.size(); ++i) {
        query += columns[i];
        if (i != columns.size() - 1) {
            query += ", ";
        }
    }
    
    query += " FROM " + table + ";";
    return query;
}

数学表示[编辑 | 编辑源代码]

字符串连接可以表示为: concat(s1,s2)=s1s2 其中表示连接操作符,结果字符串长度为: |s1s2|=|s1|+|s2|

常见问题[编辑 | 编辑源代码]

模板:Question 模板:Answer

模板:Question 模板:Answer

最佳实践[编辑 | 编辑源代码]

  • 对于简单连接:使用+=append()
  • 对于混合类型连接:使用std::stringstream
  • 避免在循环中使用+运算符
  • 预先调用reserve()可以减少内存分配次数(当知道结果字符串大小时)
std::string result;
result.reserve(100);  // 预分配空间
// ...执行多次连接操作...