给你一个目标串,请查找再给目标串中是否存在模式串,存在就输出第一个模式串在目标串中出现的位置C++
时间: 2024-03-09 22:45:49 浏览: 28
以下是一个用 C++ 编程查找目标串中是否存在模式串的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int findSubstring(string s, string p) {
int n = s.size();
int m = p.size();
for (int i = 0; i <= n - m; i++) {
bool match = true;
for (int j = 0; j < m; j++) {
if (s[i+j] != p[j]) {
match = false;
break;
}
}
if (match) {
return i;
}
}
return -1;
}
int main() {
string s = "hello world";
string p = "world";
int pos = findSubstring(s, p);
if (pos != -1) {
cout << "The pattern is found at position " << pos << " in the target string." << endl;
} else {
cout << "The pattern is not found in the target string." << endl;
}
return 0;
}
```
该程序定义了一个 `findSubstring` 函数,该函数接受两个字符串参数 `s` 和 `p`,分别表示目标串和模式串,返回模式串在目标串中第一次出现的位置。在函数内部,我们使用两个嵌套循环来遍历目标串中的所有可能的子串,对于每个子串,我们使用另一个循环来逐个比较它和模式串中的字符是否相同。如果所有字符都相同,说明找到了模式串,返回它在目标串中的位置。
在主程序中,我们定义了一个目标串 `s` 和一个模式串 `p`,然后调用 `findSubstring` 函数来查找模式串在目标串中的位置。如果模式串存在,我们输出它在目标串中的位置,否则输出未找到的提示信息。
注意,该程序只查找模式串在目标串中的第一次出现位置,如果需要查找所有出现位置,可以在函数内部使用一个向量来保存所有位置。此外,该算法的时间复杂度为 $O(nm)$,其中 $n$ 和 $m$ 分别为目标串和模式串的长度,因此在实际应用中可能需要使用更高效的算法来处理大规模数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)