C++ 子串匹配主串
作者:互联网
暴力匹配
#include <iostream>
#include <string>
using namespace std;
int strTsr(string haystack, string needle)
{
if (needle.empty())
return 0;
int n = haystack.size();
int m = needle.size();
for (int i = 0; i < n; ++i)
{
int pos = i;
for (int j = 0; j < m; ++j)
{
if (needle[j] != haystack[pos++])
{
break;
}
else
{
if (j == (m - 1))
{
return i;
}
}
}
}
return -1;
}
int main()
{
int asn = strStr("ABCDABCDE", "ABCDE");
if (asn == 0)
{
cout << "匹配的子串为空!" << endl;
}
else if (asn == -1)
{
cout << "子串不匹配主串!" << endl;
}
else
{
cout << "子串匹配了主串,开始位置:" << asn << endl;
}
return 0;
}
标签:子串,主串,return,int,needle,pos,C++,++,haystack 来源: https://www.cnblogs.com/zhouxuzhi/p/15949595.html