使用数据类型 char 对字符串中的字符串进行计数



大家好!我有这样一个问题的代码,可以创建一个程序来计算第二个字符串在第一个字符串上出现的次数。是的,如果您只输入 1 个字母,则算数,但如果您输入 2 个字母,则是一个错误。举个例子。如果第一个字符串是 Harry Partear,第二个字符串是 ar,则必须计为 3。代码如下:

#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
char first [100], second;
int count;
cout <<"Enter 1st String: ";
cin.get (first, 100);
cout <<"Enter 2nd String: ";
cin >> second;
for (int i = 0; i < strlen (first); i++)
{
    if (tolower(first[i]) == tolower(second))
    {
                          count++;
                          }
                          }

cout << "THE STRING " << "'" << second << "'" << " appeared " << count 
<< " times in "     << first << ".";
getch ();
return 0;
}

希望有人能帮助我。 :(

第一个问题是你的second变量被声明为单个char,而不是字符串。这是它应该是:

char first[100], second[100];

second前面的[100]适用于first,而不是firstsecond,即使这两者被声明为一个声明的一部分。second的类型仍然是标量char

现在second是一个字符数组,让我们解决第二个问题:你也需要像对待数组一样对待second。特别是,您需要添加一个嵌套循环来遍历second,以便比较看起来像

if (tolower(first[i]) == tolower(second[j]))

j 是嵌套循环的索引。

最后,您需要一个标志来指示 second 的所有字符都与 first 的字符匹配。将此标志设置为嵌套循环之前的true,然后在发现不匹配时将其设置为 false。如果该标志在循环后仍然true,则递增count

尝试更改它,如下所示:

char first [100], second[100];
int count;
cout <<"Enter 1st String: ";
cin.get (first, 100);
cout <<"Enter 2nd String: ";
cin.get (second, 100);
for (int i = 0; i < strlen (first); i++)
{
    for (int j = 0; j < strlen (second); i++)
    {
        if (tolower(first[i]) == tolower(second[j]))
        {
                          count++;
                          }
                          }
                          }

但现在的问题是,程序不会提示用户输入第二个字符串。伤心。哈哈哈。:(

最新更新