Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++字符串拼接

作者:夏威夷丶霪男   发布日期:2025-03-07   浏览:337

#include <iostream>
#include <string>

int main() {
    // 使用 + 操作符拼接字符串
    std::string str1 = "Hello";
    std::string str2 = "World";
    std::string result1 = str1 + " " + str2;
    std::cout << "使用 + 拼接: " << result1 << std::endl;

    // 使用 += 操作符拼接字符串
    std::string result2 = "Hello";
    result2 += " ";
    result2 += "World";
    std::cout << "使用 += 拼接: " << result2 << std::endl;

    // 使用 append 方法拼接字符串
    std::string result3 = "Hello";
    result3.append(" ").append("World");
    std::cout << "使用 append 拼接: " << result3 << std::endl;

    // 使用 stringstream 拼接字符串
    std::stringstream ss;
    ss << "Hello" << " " << "World";
    std::string result4 = ss.str();
    std::cout << "使用 stringstream 拼接: " << result4 << std::endl;

    return 0;
}

解释说明

  1. 使用 + 操作符拼接字符串:

    • + 操作符可以直接将两个 std::string 对象连接在一起,也可以连接一个 std::string 和一个 C 风格的字符串或字符。
    • 示例中将 "Hello""World" 通过 + 操作符连接,并在中间添加了一个空格。
  2. 使用 += 操作符拼接字符串:

    • += 操作符用于将一个字符串追加到另一个字符串的末尾。
    • 示例中先初始化了字符串 "Hello",然后分别用 += 追加了空格和 "World"
  3. 使用 append 方法拼接字符串:

    • appendstd::string 类的一个成员函数,用于将一个字符串追加到当前字符串的末尾。
    • 示例中先初始化了字符串 "Hello",然后调用 append 方法依次追加了空格和 "World"
  4. 使用 stringstream 拼接字符串:

    • std::stringstream 是一个非常灵活的工具,可以方便地进行字符串的格式化操作。
    • 示例中创建了一个 stringstream 对象,并使用 << 操作符将多个字符串片段插入到流中,最后通过 str() 方法获取拼接后的字符串。

上一篇:c++容器

下一篇:c++ 引用

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

c++ weak_ptr

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站