目录
一.find方法基本用法
1.查找字符
2.查找子字符串
3.查找子字符串(从指定位置开始)
4.查找字符范围
5.查找不包含特定字符的范围
二.使用string::npos返回无效位置
三.总结
在C++中, std::string 类的 find 成员函数用于查找子字符串在字符串中的位置。 find 函数有多个重载版本,允许你以不同的方式执行查找操作。
一.find方法基本用法 - #include <iostream>
- #include <string>
- int main() {
- std::string str = "Hello World!";
- size_t pos = str.find("World");
- if (pos != std::string::npos) {
- std::cout << "Found 'World' at position: " << pos << std::endl;
- } else {
- std::cout << "The substring 'World' was not found." << std::endl;
- }
- return 0;
- }
复制代码
在这个示例中, find 被用来查找子字符串 "World" 在字符串 str 中的位置。如果找到了, pos 将包含子字符串的起始索引;如果没有找到, pos 将被设置为 std::string::npos 。 |