最常用方法是使用std::string的find函数查找子串位置,返回首次出现的索引或std::string::npos表示未找到;可通过指定起始位置进行多次查找,结合循环可找出所有匹配位置,包括重叠情况;此外还提供rfind、find_first_of等变体函数用于不同匹配需求。

在C++中查找字符串中子串的位置,最常用的方法是使用标准库 std::string 提供的 find 函数。这个函数能快速定位子串首次出现的位置,如果找不到则返回一个特殊值。
使用 find 查找子串位置
std::string 的 find 成员函数可以用来查找子串、字符或 C 风格字符串在原字符串中的位置。它返回匹配位置的索引(从0开始),若未找到则返回 std::string::npos。
#include
#include
int main() {
std::string str = "Hello, welcome to C++ programming!";
std::string substr = "welcome";
size_t pos = str.find(substr);
if (pos != std::string::npos) {
std::cout << "子串位置: " << pos << std::endl;
} else {
std::cout << "未找到子串" << std::endl;
}
return 0;
}
输出结果:子串位置: 7
查找从指定位置开始的子串
你也可以让查找从某个特定位置开始,避免重复查找前面的内容。只需给 find 传入起始索引即可。
立即学习“C++免费学习笔记(深入)”;
size_t pos = str.find("C++", 8); // 从位置8开始查找
这在循环查找多个匹配时非常有用。
查找所有匹配的子串位置
如果想找出所有出现的位置,可以用循环不断调用 find,每次从上一次找到的位置后一位开始。
std::string text = "ababa";
std::string target = "aba";
size_t pos = 0;
while ((pos = text.find(target, pos)) != std::string::npos) {
std::cout << "找到位置: " << pos << std::endl;
pos += 1; // 移动一位继续找重叠匹配
}
这段代码会输出位置 0 和 2,因为存在重叠匹配。
其他查找函数
除了 find,std::string 还提供了一些变体函数:
- rfind():从右往左查找,返回最后一次出现的位置
- find_first_of():查找任意一个匹配字符的首次出现
- find_last_of():查找任意一个匹配字符的最后一次出现
- find_first_not_of():查找第一个不匹配的字符
- find_last_not_of():查找最后一个不匹配的字符
这些函数适合处理更复杂的字符匹配场景。
基本上就这些。对于大多数子串查找需求,find 已经足够高效和易用。注意检查返回值是否为 std::string::npos,避免误用无效位置。不复杂但容易忽略细节。











