字符串中字母的字母排序 C

alphabetical sort of letters in a string C

我是 C 编程的新手,正在尝试编写一个程序来按字母顺序对用户输入的一串字母进行排序。到目前为止,我有以下代码。任何人都可以帮助我正确地将其设置为 运行 吗?代码编译和 运行s,但似乎没有正确存储 运行ning 计数。

就调试而言,我注意到使用字母作为计数器可能是个问题,但我在其他地方看到过这样做,他们的 code 编译并且 运行 没问题。提前致谢。

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

int main(int argc, char *argv[])
{
        char str[10], strout[10] ;
        char letter ;
        int letter_count[26] = {0} ;
        int i, j , k, l, strlength ;

        printf("Please enter a string and I'll sort it \n") ;
        fgets(str, sizeof(str), stdin) ;
        strlength = strlen(str) ;

        for(i = 0 ; i < strlength ; i++)
        {
                if((str[i] >= 'A') && (str[i] <= 'Z'))
                {
                        printf("Capital letter\n") ;
                        letter  = str[i] - 'A' ;
                        letter_count[letter] = letter_count[l] + 1  ;
                        printf("Letter %c has a count of %d\n",str[i], letter_count[i]) ;
                }
                else if((str[i] >= 'a') && (str[i] <= 'z'))
                {
                        printf("Lower case\n") ;
                        letter = str[i] - 'a' ;
                        letter_count[letter] = letter_count[l] + 1 ;
                        printf("Letter %c has a count of %d\n",str[i], letter_count[i]) ;
                }
        }

        k = 0 ;
        for( letter = 'a' ; letter <= 'z' ; letter++)
        {
                i = letter - 'a' ;
                for(j = 0 ; j <= letter_count[i] ; j++)
                {
                        strout[k] = letter ;
                        k++ ;
                }


        }
        return 0 ;
}

您的代码中存在几个错误:

  1. 以下在 for 循环中出现两次的行是不正确的:

    letter_count[letter] = letter_count[l] + 1  ;
    

    变量l 从未被初始化。 正确的是,例如:

    letter_count[letter]++;
    
  2. 下面也是错误的:

    printf("Letter %c has a count of %d\n",str[i], letter_count[i]) ;
    

    字母的计数在 letter_count[letter] 中而不是在 letter_count[i] 中。

  3. 循环终止条件中有一个off-by-one error

    for(j = 0 ; j <= letter_count[i] ; j++)
    

    应该改成j < letter_count[i],否则每个字母多算一次