按用户输入C的顺序返回ASCII字符的计数

问题描述 投票:-2回答:1

我需要按照用户输入接收到的字符数组的顺序返回ASCII字符数

我目前的解决方案是在ASCII表上按其外观的升序返回字符,而不是按用户输入的顺序

#include <stdio.h>
#include <string.h>

int main()
{
  char string[16];
  int c = 0, count[128] = {0}, x, counted = 0;

  printf("Enter a word>\n");
  scanf("%s", string);

  while (string[c] != '\0') {
    if(string[c] >= '!' && string[c] <= '~'){
      x = string[c] - '!';
      count[x]++;
    }
    c++;
  }

  for (c = 0; c < 128; c++){
    if(count[c] > 1){
    printf("Duplicate letter: %c, Occurrences: %d\n", c + '!', count[c]);
      counted++;
    }
  }

  if(counted < 1){
    printf("No duplicates found\n");
  }
  return 0;
}

输入示例:

AAAAaaaaBBBbb99

期望的输出:

重复的字母:A,出现次数:4 重复的字母:a,出现次数:4 重复字母:B,出现次数:3 重复的字母:b,出现次数:2 重复字母:9,出现次数:2

我目前的(错误的)输出:

重复字母:9,出现次数:2 重复的字母:A,出现次数:4 重复字母:B,出现次数:3 重复的字母:a,出现次数:4 重复的字母:b,出现次数:2 非常感谢任何帮助

c arrays character ansi
1个回答
0
投票

不是一个非常优雅的解决方案但它有效:

#include <stdio.h>
#include <string.h>

int main() {
    char string[1024];
    int c = 0;
    int count[128] = {0};
    int x;
    int counted = 0;

    printf("Enter a word:\n");
    scanf("%1023s", string);

    while (string[c] != '\0') {
        if(string[c] >= '!' && string[c] <= '~'){
            x = string[c] - '!';
            count[x]++;
        }
        c++;
    }

    int j = 0;
    while (string[j] != '\0') {
        int ch = string[j] - '!';

        if(count[ch] > 1){
            printf("Duplicate letter: %c, Occurrences: %d\n", ch + '!', count[ch]);
            count[ch] = -1;
            counted++;
        }

        j++;
    }

    if(counted < 1){
        printf("No duplicates found.\n");
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.