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

c++ string类的常用方法

作者:酷帥男爵   发布日期:2025-07-12   浏览:82

#include <iostream>
#include <string>

using namespace std;

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

    // 1. size() - 获取字符串长度
    cout << "Size of str1: " << str1.size() << endl; // 输出: 13

    // 2. empty() - 检查字符串是否为空
    string str2 = "";
    if (str2.empty()) {
        cout << "str2 is empty" << endl; // 输出: str2 is empty
    }

    // 3. append() - 追加字符串
    str1.append(" Welcome!");
    cout << "After appending: " << str1 << endl; // 输出: Hello, World! Welcome!

    // 4. substr() - 获取子字符串
    string subStr = str1.substr(0, 5);
    cout << "Substring from index 0 to 4: " << subStr << endl; // 输出: Hello

    // 5. find() - 查找子字符串的位置
    size_t pos = str1.find("World");
    if (pos != string::npos) {
        cout << "Position of 'World': " << pos << endl; // 输出: Position of 'World': 7
    }

    // 6. replace() - 替换子字符串
    str1.replace(7, 5, "Universe");
    cout << "After replacing 'World' with 'Universe': " << str1 << endl; // 输出: Hello, Universe! Welcome!

    // 7. erase() - 删除子字符串
    str1.erase(14, 8); // 删除从索引14开始的8个字符
    cout << "After erasing: " << str1 << endl; // 输出: Hello, Universe!

    // 8. compare() - 比较两个字符串
    string str3 = "Hello, Universe!";
    if (str1.compare(str3) == 0) {
        cout << "str1 and str3 are equal" << endl;
    } else {
        cout << "str1 and str3 are not equal" << endl; // 输出: str1 and str3 are equal
    }

    return 0;
}

解释说明:

  1. size(): 返回字符串的长度。
  2. empty(): 检查字符串是否为空,返回布尔值。
  3. append(): 在字符串末尾追加另一个字符串。
  4. substr(): 提取从指定位置开始的子字符串,可以指定长度。
  5. find(): 查找子字符串在字符串中的位置,返回其起始索引。如果未找到,则返回 string::npos
  6. replace(): 替换指定范围内的子字符串为新的字符串。
  7. erase(): 删除指定范围内的子字符串。
  8. compare(): 比较两个字符串,返回0表示相等,负数表示小于,正数表示大于。

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

上一篇:c++小游戏编程代码

下一篇:c++语言程序设计

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

c++ weak_ptr

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

Laravel 中文站