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

string在c++中的用法

作者:娚人ゝ無須赫赫有名   发布日期:2025-09-21   浏览:30

#include <iostream>
#include <string>

using namespace std;

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

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

    // 使用构造函数初始化字符串
    string str3(10, 'a');
    cout << "String initialized with 10 'a's: " << str3 << endl;

    // 字符串连接
    string str4 = str2 + " Welcome to C++";
    cout << "Concatenated string: " << str4 << endl;

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

    // 访问单个字符
    cout << "First character of str4: " << str4[0] << endl;

    // 子字符串
    string subStr = str4.substr(7, 5);
    cout << "Substring from index 7 with length 5: " << subStr << endl;

    // 查找子字符串
    size_t pos = str4.find("C++");
    if (pos != string::npos) {
        cout << "Found 'C++' at position: " << pos << endl;
    } else {
        cout << "'C++' not found" << endl;
    }

    // 替换子字符串
    str4.replace(7, 6, "C++ Programming");
    cout << "After replacing substring: " << str4 << endl;

    return 0;
}

解释说明:

  1. 创建和初始化字符串

    • string str1; 创建一个空字符串。
    • string str2 = "Hello, World!"; 使用字符串字面量初始化字符串。
    • string str3(10, 'a'); 使用构造函数初始化包含10个字符'a'的字符串。
  2. 字符串操作

    • str2 + " Welcome to C++":将两个字符串连接在一起。
    • str4.length():获取字符串的长度。
    • str4[0]:访问字符串中的单个字符。
    • str4.substr(7, 5):提取从索引7开始,长度为5的子字符串。
    • str4.find("C++"):查找子字符串的位置。
    • str4.replace(7, 6, "C++ Programming"):替换指定范围内的子字符串。

通过这些示例代码,您可以了解在C++中如何使用std::string类进行常见的字符串操作。

上一篇:c++ string split

下一篇:c++浮点数

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

队列c++

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

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

Laravel 中文站