C++ 实现子字符串查找:高效定位所有匹配位置
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> findSubstr(string s, string t) {
vector<int> positions;
int n = s.size();
int m = t.size();
for (int i = 0; i <= n - m; i++) {
bool found = true;
for (int j = 0; j < m; j++) {
if (tolower(s[i+j]) != tolower(t[j])) {
found = false;
break;
}
}
if (found) {
positions.push_back(i);
}
}
return positions;
}
int main() {
string s, t;
getline(cin, s);
getline(cin, t);
vector<int> positions = findSubstr(s, t);
if (positions.empty()) {
cout << -1 << endl;
} else {
for (int pos : positions) {
cout << pos << endl;
}
}
return 0;
}
代码功能:
本代码实现了一个名为 findSubstr 的函数,用于查找子字符串 t 在父字符串 s 中的所有出现位置。
代码解释:
- 函数
findSubstr接收两个字符串参数s和t,分别代表父字符串和子字符串。 - 循环遍历父字符串
s,从索引 0 开始,每次移动t的长度。 - 在每个位置,循环比较子字符串
t和父字符串s的对应字符,如果所有字符都匹配,则将该位置添加到结果向量positions中。 - 函数返回结果向量
positions,包含所有子字符串t在父字符串s中出现的起始位置。 - 在
main函数中,读取用户输入的父字符串和子字符串,调用findSubstr函数进行查找,并打印结果。
使用方法:
- 将代码保存为
.cpp文件,例如find_substring.cpp。 - 使用 C++ 编译器编译代码,例如
g++ find_substring.cpp -o find_substring。 - 运行可执行文件,例如
./find_substring。 - 在程序运行时,分别输入父字符串和子字符串,程序会输出所有匹配位置。
示例:
输入:
Go Abc good goole!
go
输出:
8
13
输入:
Go Abc good goole!
hi
输出:
-1
说明:
本代码使用循环和字符比较的方式进行子字符串查找,效率较高,适用于各种场景下的字符串匹配任务。你可以根据实际需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/pcSZ 著作权归作者所有。请勿转载和采集!