我的任务是计算 char 字符串中子字符串的出现次数。我写了这段代码,但在某些输入上输出是错误的。就像字符串是“hassana”而 sub 是“as”然后它输出 2 ...请有人帮助我
int CharString :: countOccurenceOf(const char* substr)
{
int count = 0;
bool find = false;
for(int i = 0; i < size1; i++)
{
if(cstr[i] == substr[0])
{
int x = i;
int c = 1;
find = true;
while ( substr[c] != '\0' && find == true && (x+1) < size1)
{
if(cstr [x+1] != substr[c])
{
find = false;
}
c++;
x++;
}
if (find == true)
{
count++;
i = i + c-1;
}
}
}
return count;
}
有一些解决方案......可以吗?
int CharString :: countOccurenceOf(const char* substr)
{
int len = 0;
if ( substr != '\0')
{
while( substr[len] != '\0')
len++;
}
int count = 0;
bool find = false;
for(int i = 0; i < size1; i++)
{
if(cstr[i] == substr[0])
{
int x = i;
int c = 1;
find = true;
while ( substr[c] != '\0' && find == true && (x+1) < size1)
{
if(cstr [x+1] != substr[c])
{
find = false;
}
c++;
x++;
}
if (find == true && c == len)
{
count++;
i = i + c-1;
}
}
}
return count;
最佳答案
问题是如果 x+1 < size1,你会自动中断。如果子字符串的第一个字符与主字符串的最后一个字符匹配,那么这将自动中断并且“find”仍将设置为 true,因此您将匹配增加 1。有多种方法可以更改代码以修复这个问题;既然您知道问题出在哪里,希望您能找到一个。
关于c++ - 计算子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021819/