2014-03-26 29 views
0

我在C中排序字符时遇到了一些问题。如果我想按从z到a的字母顺序对数组进行排序,它的工作原理很好。当我尝试做相反,从A到Z,它不工作。我可以利用一些帮助,谢谢;)C按字母顺序排列无论哪种

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

int main() { 
    char s1[10],a; 
    int i,t; 
    printf("enter a set to sort: "); 
    scanf("%s",s1); 
    t=1; 
// printf("%d length of set",strlen(s1)); 
    while (t==1) 
    { 
//  printf("a\n"); 
     t=0; 
     for (i=0;i<strlen(s1);i++) 
      { 
       if (s1[i]<s1[i+1]) 
       { 
//    printf("s"); 
       t=1; 
       a=s1[i+1]; 
       s1[i+1]=s1[i]; 
       s1[i]=a; 
       } 
      } 
    } 
    printf("%s sorted",s1); 
} 

回答

0

如果只使用1个循环,则不会对所有组合进行排序。所以使用冒泡排序逻辑。

while (t==1) 
    { 
//  printf("a\n"); 
     t=0; 
     for (i=0;i<strlen(s1)-1;i++) 
      { 
       for(j=0;j<strlen(s1)-1-i;j++) 
       { 
       if (s1[j]<s1[j+1]) 
       { 
//    printf("s"); 
       t=1; 
       a=s1[j+1]; 
       s1[j+1]=s1[j]; 
       s1[j]=a; 
       } 
       } 
      } 
    } 
+0

作品,谢谢! :) – user3395711

+0

@ user3395711好的。阅读[this](http://stackoverflow.com/about)了解如何使用stackoverflow.accept一个正确的答案和投票任何有用的答案 – LearningC

1

这里有一个很大的问题:

if (s1[i]<s1[i+1]) 

这将比较带字符串终止符的字符串中的最后一个字符。所以你会排序你的字符串包括字符串终止符,这不是你想要的。

+0

它不会,因为 “我” 将达到一个最大值感谢“i user3395711

+0

dejvid @ dejvid-Aspire-V5-431〜/ Desktop/C/test $ ./test 输入设置排序:abcdefg 7的长度集合 gfedcba排序 – user3395711

+1

@ user3395711检查,'我

0

仅供参考,在C做这个理想的方式是这样的:

#include <stdlib.h>   // qsort 
#include <ctype.h>   // toupper 
#include <stdio.h>   // printing 

int chrcmp (const void* obj1, const void* obj2) 
{ 
    char ch1 = *(const char*)obj1; 
    char ch2 = *(const char*)obj2; 

    ch1 = toupper(ch1);  // remove case-sensitivity 
    ch2 = toupper(ch2); 

    return ch1 - ch2;   // integer promotion will make this int implicitly 
} 


int main() 
{ 
    char str[] = "Sort letters and symbols alphabetically"; 

    puts(str); 

    qsort (str,    // the array to sort 
     sizeof(str)-1,  // the number of items in the array (minus nullterm) 
     sizeof(char),  // the size of each item 
     chrcmp);   // comparison function 

    puts(str); 

    return 0; 
} 

输出:

Sort letters and symbols alphabetically 
    aaaabbcdeeehilllllmnooprrSsssttttyy