c++

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

小樊
83
2024-08-28 02:35:54
栏目: 编程语言

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

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

示例:

#include<iostream>
#include<string>

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<iostream>
#include<string>

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

示例:

#include<iostream>
#include<string>

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<iostream>
#include<string>
#include<string_view>

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;
}

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

0
看了该问题的人还看了