c - 字符串 C 中字母按字母顺序排序

标签 c sorting alphabetical

我是 C 编程新手,正在尝试编写一个程序来对用户输入的字母字符串按字母顺序进行排序。到目前为止我有以下代码。谁能帮助我让它正常运行?该代码可以编译并运行,但似乎无法正确存储运行计数。

就调试而言,我注意到使用字母作为计数器可能是一个问题,但在其他地方看到过这样做,他们的 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]否则,您对每个字母的计数会比需要的多一次。

关于c - 字符串 C 中字母按字母顺序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330895/

相关文章:

c - 如何按字母顺序对字符串数组进行排序(区分大小写,非标准排序规则)

php - 在 A-Z 列表中回显数组

c - 使用C查找文件权限

c - codechef 上的 C 代码出现 NZEC 错误

c - GDB 函数参数条件中断

java - 按花色对一副纸牌进行排序然后排名

c - 尝试使用调用 stat 的 ctime 返回值对 c 中的结构数组进行排序

regex - 如何按长度对一系列行进行排序?

python - 如何检查 3 个字符是否按连续的字母顺序排列

c - 在 C 中使用 getch() 时,当没有当前窗口错误时尝试绘制操作