std::string::find是C++中查找子串最直接的方法,返回首次匹配位置或npos表示未找到,支持从指定位置开始查找以实现多重匹配;处理未找到情况需比较返回值与std::string::npos;其性能通常足够高效,底层可能采用Boyer-Moore等优化算法,适用于大多数场景;对于复杂模式可选用std::regex,而find_first_of等函数可用于字符集匹配,std::search提供自定义比较的泛型查找能力。

在C++中查找字符串中的子串,最直接且推荐的方法是利用
std::string
find
要查找一个
std::string
std::string::find
find
size_t find(const std::string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
其中:
立即学习“C++免费学习笔记(深入)”;
str
s
pos
如果找到了子串,
find
size_t
std::string::npos
这是一个简单的例子:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, world! This is a test string.";
std::string sub1 = "world";
std::string sub2 = "C++";
size_t found_pos1 = text.find(sub1);
if (found_pos1 != std::string::npos) {
std::cout << "'" << sub1 << "' found at index: " << found_pos1 << std::endl;
} else {
std::cout << "'" << sub1 << "' not found." << std::endl;
}
size_t found_pos2 = text.find(sub2);
if (found_pos2 != std::string::npos) {
std::cout << "'" << sub2 << "' found at index: " << found_pos2 << std::endl;
} else {
std::cout << "'" << sub2 << "' not found." << std::endl;
}
// 从特定位置开始查找
std::string text_repeat = "banana split banana";
size_t first_banana = text_repeat.find("banana"); // 0
size_t second_banana = text_repeat.find("banana", first_banana + 1); // 13
std::cout << "First 'banana' at: " << first_banana << std::endl;
std::cout << "Second 'banana' at: " << second_banana << std::endl;
return 0;
}std::string::find
当我们在一个长字符串中寻找子串时,子串可能出现不止一次,或者根本不存在。
std::string::find
如果我们需要找出所有匹配项,或者确认子串不存在,
find
处理多重匹配: 要查找所有出现的子串,我们需要在一个循环中反复调用
find
pos
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string sentence = "apple banana apple orange apple";
std::string target = "apple";
std::vector<size_t> positions;
size_t current_pos = sentence.find(target, 0); // 从0开始查找
while (current_pos != std::string::npos) {
positions.push_back(current_pos);
// 更新查找位置:从当前找到位置的下一个字符开始
current_pos = sentence.find(target, current_pos + 1);
}
if (!positions.empty()) {
std::cout << "'" << target << "' found at positions: ";
for (size_t pos : positions) {
std::cout << pos << " ";
}
std::cout << std::endl;
} else {
std::cout << "'" << target << "' not found." << std::endl;
}
return 0;
}这段代码清晰地展示了如何通过迭代来捕获所有匹配。每次找到一个,我们就把起始位置向前推进,直到
find
npos
处理未找到子串的情况: 这相对简单。正如我们前面提到的,如果
find
std::string::npos
find
std::string::npos
#include <iostream>
#include <string>
int main() {
std::string text = "Programming is fun.";
std::string not_found_sub = "Java";
size_t result = text.find(not_found_sub);
if (result == std::string::npos) {
std::cout << "'" << not_found_sub << "' was not found in the text." << std::endl;
} else {
std::cout << "'" << not_found_sub << "' found at index: " << result << std::endl;
}
return 0;
}这种模式是C++字符串查找中非常基础且重要的判断方式,可以说,它是我们判断查找结果的“黄金标准”。
std::string::find
谈到性能,这又是一个值得深思的问题了。我们经常会想,一个库函数到底有多高效?
std::string::find
std::string::find
std::string::find
std::string::find
何时需要考虑优化? 不过,凡事没有绝对。在一些极端场景下,你可能会开始思考是否有更快的办法:
find
find
std::regex
性能优化的一些方向(当find
std::regex
std::regex_search
std::regex_match
std::string::find
find
总而言之,对于日常的C++开发工作,
std::string::find
find
除了我们常用的
std::string::find
rfind
std::string::find_first_of
std::string::find_last_of
find_first_of
find_last_of
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World! 123";
std::string delimiters = ",! "; // 查找逗号、感叹号或空格
size_t pos_first_delimiter = s.find_first_of(delimiters);
if (pos_first_delimiter != std::string::npos) {
std::cout << "First delimiter found at: " << pos_first_delimiter << std::endl; // Output: 5 (for ',')
}
size_t pos_last_delimiter = s.find_last_of(delimiters);
if (pos_last_delimiter != std::string::npos) {
std::cout << "Last delimiter found at: " << pos_last_delimiter << std::endl; // Output: 12 (for ' ')
}
return 0;
}std::string::find_first_not_of
std::string::find_last_not_of
find_first_of
#include <iostream>
#include <string>
int main() {
std::string s_trimmed = " Hello World ";
std::string whitespace = " \t\n\r";
size_t first_non_whitespace = s_trimmed.find_first_not_of(whitespace);
size_t last_non_whitespace = s_trimmed.find_last_not_of(whitespace);
if (first_non_whitespace != std::string::npos && last_non_whitespace != std::string::npos) {
std::string trimmed_s = s_trimmed.substr(first_non_whitespace, last_non_whitespace - first_non_whitespace + 1);
std::cout << "Trimmed string: '" << trimmed_s << "'" << std::endl; // Output: 'Hello World'
}
return 0;
}std::search
std::search
<algorithm>
std::string::find
std::search
#include <iostream>
#include <string>
#include <algorithm> // For std::search
#include <vector>
int main() {
std::string text = "abracadabra";
std::string pattern = "cad";
auto it = std::search(text.begin(), text.end(), pattern.begin(), pattern.end());
if (it != text.end()) {
std::cout << "Pattern found at index: " << std::distance(text.begin(), it) << std::endl; // Output: 4
} else {
std::cout << "Pattern not found." << std::endl;
}
// 带有自定义比较的例子 (例如,忽略大小写)
std::string text_case = "Hello World";
std::string pattern_case = "world";
auto it_case = std::search(text_case.begin(), text_case.end(),
pattern_case.begin(), pattern_case.end(),
[](char c1, char c2){
return std::tolower(c1) == std::tolower(c2);
});
if (it_case != text_case.end()) {
std::cout << "Case-insensitive pattern found at index: " << std::distance(text_case.begin(), it_case) << std::endl; // Output: 6
}
return 0;
}std::search
std::regex_search
std::regex_search
<regex>
#include <iostream>
#include <string>
#include <regex> // For std::regex
int main() {
std::string text = "My email is test@example.com and another is user@domain.net";
std::regex email_pattern(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)"); // 匹配邮箱地址的正则表达式
std::smatch match;
if (std::regex_search(text, match, email_pattern)) {
std::cout << "Found email: " << match.str(0) << std::endl; // Output: test@example.com
}
// 查找所有匹配项
std::string::const_iterator search_start(text.cbegin());
while (std::regex_search(search_start, text.cend(), match, email_pattern)) {
std::cout << "Found email: " << match.str(0) << std::endl;
search_start = match.suffix().first; // 更新搜索起始位置
}
// Output:
// Found email: test@example.com
// Found email: user@domain.net
return 0;
}在我看来,掌握
std::regex
选择哪种方法,最终还是取决于你的具体需求:是简单的子串查找,还是需要匹配字符集,抑或是复杂的模式。每种工具都有其最适合的场景。
以上就是如何在C++中查找字符串中的子串_C++子串查找函数使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号