在文本中查找半个单词"ABBA"的问题



显示以下赋值:

给定一个字符串。计算"ABBA"在其中的使用次数。

我的代码:

#include<iostream>
#include<string>
using namespace std;
int main()
{
string aBBa = "Abbakiy Abbakum Abbak'evich";
int i = 0, j = 0;
cout << "Expression: " << aBBa << endl;
do {
if (aBBa[i] == 'а')
j++;
i++;
} while (aBBa[i] != '');
cout << "Quantity letters a: " << j << endl;
i = 0;
system("pause");
return 0;
}

我只能理解如何在文本中找到字母的数量,如果我试图用同样的方式找到它的半个单词(即,在下面的片段中,我会写而不是-abba(,

if (aBBa[i] == 'а')
j++;

则程序将拒绝计算任何值(该值将为零(。

示例

#include<iostream>
#include<string>
int main()
{
std::string needle = "Abba";
std::string haystack = "Abbakiy Abbakum Abbak'evich";
int i = 0, j = 0, count = 0;
std::cout << "Expression: " << haystack << std::endl;
do {
if (haystack[i] == needle[j])
{
j++;
if (j == needle.size())
{
++count;
j = 0;
}
}
else
j = 0;
i++;
} while (haystack[i] != '');
std::cout << "Needles in the haystack: " << count << std::endl;
return 0;
}

有几个问题可以解释为什么using namespace std;system("pause");是有害的。不要使用它们。

最新更新