检查字符串中每个字符出现的问题

Problems in checking for occurence of each character in a string

本文关键字:问题 字符 字符串 检查      更新时间:2023-10-16

我正在尝试制作一个程序,该程序计算字符串中每个每个字符的情况,例如:

Enter string: hello world

输出为

h: 1
e: 1
l: 3
o: 2

...等等

,但我的输出似乎遍布全部,例如:

Enter string: nice on ice
n: 2
i: 2
c: 1
e: 1 //there should be 2 e's
o: 1

有时喜欢:

Enter string: potato
p: 1
o: 2
t: 2
a: 1
: 1

这是我的代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
  char l, str[30], cpy[30];
  int i, j, occ;
  i = j = 0;
  occ = 0;
  cout << "Enter string: ";
  fgets(str, 10, stdin);
  strcpy(cpy, str); // copy the string as I am about to modify it
  // Checks for occurences of each character.
  // Every character found is changed to a ' ' so that it isn't counted again
  while (str[i] != '') {
    occ = 0;
    if (str[i] != ' ') {
      l = str[i];
      for (j = 0; str[j] != ''; j++) {
        if (str[j] == cpy[i] && str[j] != ' ') {
          occ++;
          str[j] = ' ';
        }
      }
      cout << l << ": " << occ <<endl;
    }
    i++;
  }
  cout << "n";
  fputs(str, stdout); // just to check if all characters were converted to ' '
  cout << "n";
  return 0;
}

您实际上不需要制作副本,并且您的内部循环正在做太多工作,迭代已经无效的字符。另外,您似乎对副本或原始内容是由ij索引的困惑。

int main()
{
    char str[30];
    int i, j, occ;
    cout << "Enter string: ";
    fgets(str, 10, stdin);
    // Checks for occurences of each character.
    // Every character found is changed to a ' ' so that it isn't counted again
    for(i = 0; str[i] != ''; i++)
    {
        if (str[i] != ' ')
        {
            // Output the current character before it is invalidated.
            cout << str[i] << ": ";
            // Start at the current character so that it is counted
            // at least once.
            occ = 0;
            for (j = i; str[j] != ''; j++)
            {
                // No need to test for ' ', because str[i] is not
                // a ' ', so equality is sufficient.
                if (str[j] == str[i])
                {
                    occ++;
                    // Invalidate each counted character.
                    str[j] = ' ';
                }
            }
            cout << occ << endl;
        }
    }
    // just to check if all characters were converted to ' '
    cout << endl << str << endl;
    return 0;
}

对于您的作业解决方案,请记住,英语字母中有26个字母,将每个字母转换为索引很容易将索引转换为数组(ASCII编码是<它是>极度简单)。

武装此信息,请考虑具有26个整数的数组,其中数组中的每个元素都是您读过的字符的计数器。

因此,只要一次在循环中一次阅读一个字符,从字符中获取反阵列索引,然后增加正确的元素。无需实际存储您阅读的文本,不需要多个检查循环。

打印时,在数组上循环并打印每个非零的元素,以及其相应的字符。