实现朴素的字符串匹配数据结构代码
时间: 2024-05-25 19:07:36 浏览: 11
实现朴素的字符串匹配算法,可以使用暴力匹配算法。具体实现方法是:从主串的第一个字符开始和模式串的第一个字符进行比较,若相等则继续比较下一个字符,若不相等则主串从下一个字符重新开始比较,直到匹配成功或者主串遍历完毕为止。
以下是实现朴素字符串匹配的C++代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int naiveSearch(string text, string pattern) {
int n = text.size();
int m = pattern.size();
for (int i = 0; i <= n - m; i++) {
bool isMatched = true;
for (int j = 0; j < m; j++) {
if (text[i + j] != pattern[j]) {
isMatched = false;
break;
}
}
if (isMatched) {
return i;
}
}
return -1;
}
int main() {
string text = "Hello, world!";
string pattern = "world";
int index = naiveSearch(text, pattern);
if (index == -1) {
cout << "Pattern not found" << endl;
} else {
cout << "Pattern found at index " << index << endl;
}
return 0;
}
```
相关推荐
![vcproj](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)