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

c++ string类

作者:花折亦无情   发布日期:2026-03-08   浏览:94

#include <iostream>
#include <string>

using namespace std;

int main() {
    // 创建一个空的 string 对象
    string str1;
    cout << "Empty string: '" << str1 << "'" << endl;

    // 使用字符串字面量初始化 string 对象
    string str2 = "Hello, World!";
    cout << "String initialized with a literal: '" << str2 << "'" << endl;

    // 使用另一个 string 对象初始化
    string str3(str2);
    cout << "String copied from another string: '" << str3 << "'" << endl;

    // 使用 substring 初始化
    string str4 = str2.substr(0, 5); // 从索引 0 开始,长度为 5 的子串
    cout << "Substring from str2: '" << str4 << "'" << endl;

    // 连接两个字符串
    string str5 = str4 + " C++";
    cout << "Concatenated string: '" << str5 << "'" << endl;

    // 修改字符串内容
    str5[0] = 'h'; // 修改第一个字符
    cout << "Modified string: '" << str5 << "'" << endl;

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

    // 查找子串
    size_t pos = str2.find("World");
    if (pos != string::npos) {
        cout << "Found 'World' in str2 at position: " << pos << endl;
    } else {
        cout << "'World' not found in str2" << endl;
    }

    // 替换子串
    str2.replace(pos, 5, "Universe");
    cout << "After replacing 'World' with 'Universe': '" << str2 << "'" << endl;

    return 0;
}

解释说明:

  1. 创建和初始化

    • string str1; 创建一个空的 string 对象。
    • string str2 = "Hello, World!"; 使用字符串字面量初始化 string 对象。
    • string str3(str2); 使用另一个 string 对象初始化新对象。
  2. 操作字符串

    • str2.substr(0, 5); 提取从索引 0 开始,长度为 5 的子串。
    • str4 + " C++"; 连接两个字符串。
    • str5[0] = 'h'; 修改字符串中的某个字符。
    • str5.length(); 获取字符串的长度。
    • str2.find("World"); 查找子串的位置。
    • str2.replace(pos, 5, "Universe"); 替换指定位置的子串。

这个示例展示了 std::string 类的一些基本功能和常见用法。

上一篇:c++ find_if

下一篇:c++ orm框架

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

c++ string类

c++ find_if

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

Laravel 中文站