string类的模糊查询
时间: 2023-10-19 16:20:22 浏览: 28
可以使用STL中的`std::string::find`函数实现模糊查询,该函数可以在一个字符串中查找另一个字符串,并返回第一个匹配到的位置。例如,以下代码可以实现在字符串`str`中查找是否包含子串`sub_str`:
```c++
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello world!";
std::string sub_str = "world";
if (str.find(sub_str) != std::string::npos) {
std::cout << "Found!" << std::endl;
} else {
std::cout << "Not found!" << std::endl;
}
return 0;
}
```
如果需要实现模糊匹配,可以在调用`find`函数之前对`sub_str`进行处理,例如将其转换为小写字母,再进行查找。完整代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str = "Hello world!";
std::string sub_str = "WORLD";
std::transform(sub_str.begin(), sub_str.end(), sub_str.begin(), ::tolower); // 转换为小写字母
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
if (str.find(sub_str) != std::string::npos) {
std::cout << "Found!" << std::endl;
} else {
std::cout << "Not found!" << std::endl;
}
return 0;
}
```
这段代码会输出`Found!`。