c++模糊查询字符串
时间: 2023-08-20 19:21:52 浏览: 47
你可以使用STL中的`std::string`和`std::find`函数来实现模糊查询字符串。
例如,如果你想查找一个字符串中是否包含另一个字符串,可以使用以下代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "hello world";
std::string query = "world";
if (str.find(query) != std::string::npos) {
std::cout << "Found!" << std::endl;
} else {
std::cout << "Not found!" << std::endl;
}
return 0;
}
```
`std::find`函数会在字符串中查找子字符串,并返回它在字符串中的位置。如果找不到子字符串,它会返回`std::string::npos`。
你还可以使用`std::search`函数来查找一个字符串中是否包含另一个字符串序列,例如:
```c++
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "the quick brown fox jumps over the lazy dog";
std::string query = "the dog";
auto result = std::search(str.begin(), str.end(), query.begin(), query.end());
if (result != str.end()) {
std::cout << "Found!" << std::endl;
} else {
std::cout << "Not found!" << std::endl;
}
return 0;
}
```
这个例子中,我们使用`std::search`函数来查找一个字符串中是否包含另一个字符串序列。`std::search`函数会在第一个字符串中查找第二个字符串序列,并返回它在第一个字符串中的位置。如果找不到字符串序列,它会返回第一个字符串的`end`迭代器。
这些函数都可以满足一定的模糊查询需求,当然也可以根据具体需求自己实现一个字符串匹配算法。