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

c++字符串函数

作者:天辰皇族   发布日期:2026-01-28   浏览:106

#include <iostream>
#include <string>

using namespace std;

int main() {
    // 创建字符串对象
    string str1 = "Hello, ";
    string str2 = "World!";

    // 字符串连接
    string str3 = str1 + str2;
    cout << "str3: " << str3 << endl;  // 输出: str3: Hello, World!

    // 获取字符串长度
    int len = str3.length();
    cout << "Length of str3: " << len << endl;  // 输出: Length of str3: 13

    // 查找子字符串的位置
    size_t pos = str3.find("World");
    if (pos != string::npos) {
        cout << "Found 'World' at position: " << pos << endl;  // 输出: Found 'World' at position: 7
    }

    // 替换子字符串
    string str4 = str3.replace(0, 6, "Hi");
    cout << "str4 after replace: " << str4 << endl;  // 输出: str4 after replace: Hi, World!

    // 插入子字符串
    str4.insert(3, " there");
    cout << "str4 after insert: " << str4 << endl;  // 输出: str4 after insert: Hi there, World!

    // 删除子字符串
    str4.erase(2, 6);
    cout << "str4 after erase: " << str4 << endl;  // 输出: str4 after erase: Hi, World!

    // 转换为大写
    for (char &c : str4) {
        c = toupper(c);
    }
    cout << "str4 in uppercase: " << str4 << endl;  // 输出: str4 in uppercase: HI, WORLD!

    return 0;
}

解释说明:

  1. 创建字符串对象:使用 std::string 类创建字符串对象。
  2. 字符串连接:使用 + 操作符将两个字符串连接在一起。
  3. 获取字符串长度:使用 length() 方法获取字符串的长度。
  4. 查找子字符串的位置:使用 find() 方法查找子字符串的位置,如果找不到返回 string::npos
  5. 替换子字符串:使用 replace() 方法替换指定位置的子字符串。
  6. 插入子字符串:使用 insert() 方法在指定位置插入子字符串。
  7. 删除子字符串:使用 erase() 方法删除指定位置的子字符串。
  8. 转换为大写:遍历字符串中的每个字符并将其转换为大写。

上一篇:c++ 泛型

下一篇:c++ 重载运算符

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

c++virtual

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

Laravel 中文站