答案是使用std::string的find、rfind、find_first_of等成员函数可高效查找子串,其中find用于查找首次出现位置,rfind查找最后一次出现位置,find_first_of查找指定字符集中的任意字符,忽略大小写需自定义转换函数。

在C++中查找子字符串有多种方法,最常用的是利用标准库中的 std::string 类提供的成员函数。这些方法简单高效,适合大多数场景。
使用 find() 方法
find() 是最常用的子字符串查找函数,它返回子串第一次出现的位置。如果未找到,返回 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 << " 找到。\n";
} else {
std::cout << "未找到子字符串。\n";
}
return 0;
}
查找最后一次出现的位置(rfind)
如果想查找子字符串最后一次出现的位置,可以使用 rfind()。
用法类似 find(),但从右往左搜索:
size_t pos = str.rfind("C++");
if (pos != std::string::npos) {
std::cout << "最后一次出现在位置 " << pos << "\n";
}
查找任意字符集合中的字符(find_first_of)
如果你想找字符串中第一个出现在指定字符集中的字符,可以用 find_first_of()。
立即学习“C++免费学习笔记(深入)”;
例如查找第一个标点符号:
std::string punct = ",.!";
size_t pos = str.find_first_of(punct);
忽略大小写的查找(自定义实现)
C++ 标准库没有直接提供忽略大小写的查找,但可以通过转换为小写后再查找实现。
示例:
std::string toLower(const std::string& s) {
std::string lower = s;
for (char& c : lower) c = std::tolower(c);
return lower;
}
std::string str_lower = toLower(str);
std::string substr_lower = toLower("WELCOME");
if (str_lower.find(substr_lower) != std::string::npos) {
std::cout << "忽略大小写找到了子串。\n";
}
基本上就这些常见用法。对于日常开发,find() 能满足大部分需求。结合 npos 判断结果,代码清晰又可靠。不复杂但容易忽略细节,比如忘记检查是否等于 npos 可能导致越界访问。










