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

c++中string的用法

作者:你不爱我就滚。   发布日期:2025-08-08   浏览:38

#include <iostream>
#include <string>

int main() {
    // 创建一个空的字符串
    std::string emptyString;
    std::cout << "Empty string: '" << emptyString << "'" << std::endl;

    // 使用构造函数创建字符串
    std::string hello("Hello, World!");
    std::cout << "Hello string: " << hello << std::endl;

    // 使用+运算符连接字符串
    std::string greeting = "Hello" + ", " + "World!";
    std::cout << "Greeting string: " << greeting << std::endl;

    // 使用append方法连接字符串
    std::string welcome = "Welcome";
    welcome.append(" to C++");
    std::cout << "Welcome string: " << welcome << std::endl;

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

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

    // 查找子字符串的位置
    size_t position = hello.find("World");
    if (position != std::string::npos) {
        std::cout << "Position of 'World': " << position << std::endl;
    } else {
        std::cout << "'World' not found." << std::endl;
    }

    // 替换子字符串
    hello.replace(7, 5, "C++");
    std::cout << "After replacing: " << hello << std::endl;

    return 0;
}

解释说明:

  1. 创建字符串

    • std::string emptyString;:创建一个空字符串。
    • std::string hello("Hello, World!");:使用构造函数创建一个包含初始值的字符串。
  2. 字符串连接

    • 使用+运算符可以将多个字符串连接在一起。
    • append方法也可以用于连接字符串,但它是通过调用对象的方法来实现的。
  3. 访问字符串中的字符

    • 可以使用数组下标的方式(如hello[0])来访问字符串中的单个字符。
  4. 获取字符串长度

    • length()方法返回字符串的长度。
  5. 查找子字符串

    • find方法用于查找子字符串的位置,如果找不到则返回std::string::npos
  6. 替换子字符串

    • replace方法用于替换指定位置和长度的子字符串。

上一篇:visual c++怎么运行程序

下一篇:c++换行指令

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++ orm框架

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ vector 清空

c++ tcp

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

Laravel 中文站