117.info
人生若只如初见

c++ string类的子串操作有哪些

C++中的std::string类提供了多种方法来获取子字符串。以下是一些常用的子串操作:

  1. substr(size_t pos = 0, size_t len = npos) const: 从给定位置pos开始,返回一个长度为len的子字符串。如果未指定len,则返回从pos开始直到字符串末尾的所有字符。

示例:

#include
#include

int main() {
    std::string str = "Hello, World!";
    std::string sub = str.substr(7, 5); // 从位置7开始,截取5个字符
    std::cout<< sub<< std::endl; // 输出 "World"
    return 0;
}
  1. operator[] (size_t pos): 通过索引访问字符串中的单个字符。这个操作符可以用于获取子字符串的特定字符,但不能直接用于获取子字符串。

示例:

#include
#include

int main() {
    std::string str = "Hello, World!";
    char ch = str[7]; // 获取位置7的字符
    std::cout << ch << std::endl; // 输出 'W'
    return 0;
}
  1. 使用迭代器和std::string构造函数创建子字符串:

示例:

#include
#include

int main() {
    std::string str = "Hello, World!";
    std::string::iterator it_begin = str.begin() + 7;
    std::string::iterator it_end = it_begin + 5;
    std::string sub(it_begin, it_end); // 从位置7开始,截取5个字符
    std::cout<< sub<< std::endl; // 输出 "World"
    return 0;
}
  1. 使用std::string_view(C++17及更高版本):

示例:

#include
#include
#include

int main() {
    std::string str = "Hello, World!";
    std::string_view sub(str.data() + 7, 5); // 从位置7开始,截取5个字符
    std::cout<< sub<< std::endl; // 输出 "World"
    return 0;
}

注意:在处理子字符串时,请确保不要越界,以避免未定义行为。

未经允许不得转载 » 本文链接:https://www.117.info/ask/feb2bAzsBBQ9VAQ.html

推荐文章

  • c# DirectoryInfo类 详解

    DirectoryInfo类是System.IO命名空间下的一个类,用于操作目录。 创建DirectoryInfo对象: DirectoryInfo dir = new DirectoryInfo(“路径”); 常用属性: FullN...

  • C# CultureInfo中常用的InvariantCulture

    在C#中,InvariantCulture是CultureInfo类中常用的一个属性。它表示一个固定不变的区域性对象,用于在不考虑当前操作系统的区域设置的情况下执行字符串操作。

  • C#中属性PropertyInfo的使用

    在C#中,PropertyInfo类用于访问和操作属性的信息。下面是PropertyInfo类常用的方法和属性的使用: Name属性:获取属性的名称。 PropertyInfo propertyInfo = my...

  • C# DialogResult的用法

    DialogResult是C#中用于表示对话框返回结果的枚举类型。它用于确定用户在对话框中点击了哪个按钮或执行了哪个操作。
    DialogResult枚举类型有以下几个常用成...

  • c字符串转换为c++ string类的方法

    在C++中,可以使用std::string构造函数将C字符串(以空字符结尾的字符数组)转换为std::string对象
    #include
    #include int main() { // 定义一个C字符...

  • string类在c++中的修改操作

    在C++中,std::string 是一个非常重要的类,它位于 头文件中。std::string` 提供了许多用于修改字符串的成员函数。以下是一些常用的修改操作: 赋值(assign)

  • c++ string类的查找功能如何使用

    C++中的std::string类提供了几种查找功能,包括find(), rfind(), find_first_of(), find_last_of()等。下面是这些函数的简单介绍和示例: size_t find(const std...

  • 如何比较c++ string类的对象

    在 C++ 中,可以使用标准库中的 std::string 类来表示字符串 相等运算符 ==:用于检查两个字符串是否相等。如果两个字符串包含相同的字符序列,则它们相等。 #in...