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

c++ 字符串函数

作者:木の兮   发布日期:2026-03-30   浏览:76

#include <iostream>
#include <string>

using namespace std;

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

    // 连接两个字符串
    string str3 = str1 + " " + str2;
    cout << "连接后的字符串: " << str3 << endl;

    // 获取字符串长度
    int length = str3.length();
    cout << "字符串长度: " << length << endl;

    // 查找子字符串的位置
    size_t position = str3.find("World");
    if (position != string::npos) {
        cout << "子字符串 'World' 的位置: " << position << endl;
    } else {
        cout << "未找到子字符串 'World'" << endl;
    }

    // 替换子字符串
    string replacedStr = str3.replace(6, 5, "C++");
    cout << "替换后的字符串: " << replacedStr << endl;

    // 字符串转为大写
    for (char &c : replacedStr) {
        c = toupper(c);
    }
    cout << "转换为大写的字符串: " << replacedStr << endl;

    return 0;
}

解释说明:

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

希望这些示例代码和解释对你有帮助!

上一篇:c++ 转义字符

下一篇:c++调用函数

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

c++ string类

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

Laravel 中文站