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

c++字符串类型

作者:依寞相随   发布日期:2025-07-21   浏览:65

#include <iostream>
#include <string>

int main() {
    // C++ 中的字符串类型是 std::string,它位于 <string> 头文件中。

    // 创建一个空字符串
    std::string emptyString;
    std::cout << "Empty string: '" << emptyString << "'" << std::endl;

    // 使用字符串字面量初始化字符串
    std::string hello = "Hello, World!";
    std::cout << "Initialized with a string literal: " << hello << std::endl;

    // 使用构造函数初始化字符串
    std::string constructedString(10, 'a'); // 构造包含 10 个 'a' 的字符串
    std::cout << "Constructed with 10 'a's: " << constructedString << std::endl;

    // 字符串拼接
    std::string firstPart = "Hello";
    std::string secondPart = "World";
    std::string combined = firstPart + ", " + secondPart + "!";
    std::cout << "Concatenated string: " << combined << std::endl;

    // 获取字符串长度
    std::cout << "Length of combined string: " << combined.length() << std::endl;

    // 访问字符串中的单个字符
    std::cout << "First character of combined string: " << combined[0] << std::endl;

    // 修改字符串中的单个字符
    combined[0] = 'J';
    std::cout << "Modified combined string: " << combined << std::endl;

    return 0;
}

解释说明:

  • std::string 是 C++ 标准库提供的字符串类,位于 <string> 头文件中。
  • 可以通过多种方式初始化字符串:空字符串、字符串字面量、构造函数等。
  • 字符串支持常见的操作,如拼接、获取长度、访问和修改单个字符等。

上一篇:c++ map添加元素的方法

下一篇:c++ dll

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

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

Laravel 中文站