使用std::string的find方法可高效查找子串,str.find(sub)返回首次出现位置,未找到则返回std::string::npos。

在C++中实现字符串查找,可以根据不同场景选择合适的方法。标准库提供了多种便捷工具,也可以手动实现基础算法以满足特定需求。
使用标准库的find函数
最简单高效的方式是利用std::string自带的find方法,它能快速定位子串或字符的位置。
-
str.find(sub)返回子串sub在str中第一次出现的索引,未找到返回std::string::npos
std::string text = "hello world";
size_t pos = text.find("world");
if (pos != std::string::npos) {
std::cout << "Found at position: " << pos << std::endl;
}使用STL算法find和search
若想用泛型算法处理字符串,可以结合中的函数。
-
std::find适合查找单个字符 -
std::search可用于查找子串,需传入两个迭代器范围
#includestd::string text = "hello world"; auto it = std::search(text.begin(), text.end(), "world", "world" + 5); if (it != text.end()) { std::cout << "Found at: " << (it - text.begin()) << std::endl; }
手动实现基础查找算法
了解底层原理时,可自己编写朴素字符串匹配算法。
立即学习“C++免费学习笔记(深入)”;
int simple_find(const std::string& str, const std::string& sub) {
if (sub.empty()) return 0;
for (size_t i = 0; i <= str.length() - sub.length(); ++i) {
bool match = true;
for (size_t j = 0; j < sub.length(); ++j) {
if (str[i + j] != sub[j]) {
match = false;
break;
}
}
if (match) return static_cast(i);
}
return -1; // not found
} 使用正则表达式进行复杂查找
对于需要模糊匹配或模式识别的场景,头文件提供强大支持。
- std::regex_search判断是否包含符合模式的子串
#includestd::string text = "Contact us at support@example.com"; std::regex email_pattern(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)"); std::smatch matches; if (std::regex_search(text, matches, email_pattern)) { std::cout << "Found email: " << matches[0] << std::endl; }
基本上就这些常用方式。日常开发推荐优先使用std::string::find,性能好且代码简洁。遇到复杂匹配再考虑正则或其他算法。手动实现有助于理解机制,但生产环境慎用。











