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

c++
1091
2024/8/28 3:31:11
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 如何在C++中使用PLOG进行调试