2014-04-07 133 views
0

按顺序排列字符串中单词的最简单方法是什么? 我做了下面的代码,但它不适用于较小的单词,它也打印了很多垃圾值。你能告诉我为什么吗?如何按字母顺序排序字符串中的单词

#include<stdio.h> 
#include<string.h> 
void main() 
{ 
    int i=0,j=0,k=0,l=0,n,wmax=0,tem; 
    char text[80]; 
    char sort[80]; 
    char temp[20]; 
    struct word // a structure to contain a single word and it's length 
    { 
     char text[10]; 
     int length; 
    } 
    word[20]; 

    printf("Enter a line of text"); 
    gets(text); 
    while(text[j]!='\0') 
    { 
     if(text[j]==' ') 
      wmax++;j++; 
    }; 
    wmax=j; 
    for(i=0;i<j;i++) 
    { 
    if(text[i]==' ') 
    { 
     word[k].text[l]='\0'; 
     k++; 
     l=0; 
     continue; 
    } 
    word[k].text[l]=text[i]; 
    word[k].length=l; 
    l++; 

} 
for(n=0;n<wmax;n++){ 
    for(i=0;i<wmax;i++) 
    { 
     for(j=0;j<word[i].length;j++) 
     { 
      if(word[i].text[j]>word[i+1].text[j]) 
      { 
       strcpy(temp,word[i].text); 
       strcpy(word[i].text,word[i+1].text); 
       strcpy(word[i+1].text,temp); 
      } 
      if(word[i].text[j]==word[i+1].text[j]) 
       continue; 
      if(word[i].text[j]<word[i+1].text[j]); 
       break; 
     } 
    } 
} 



for(j=0;j<wmax;j++){ 
    puts(word[j].text); 
} 
+0

1)制定更好的identation 2)尽量拆分字符串的话,然后的话 –

+0

这些嵌套的与无压痕排序让我头晕目眩。 – zubergu

回答

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

int cmp(const void *a, const void *b){ 
    return strcmp(*(char**)a, *(char**)b); 
} 

int main(){ 
    char text[80]; 
    char *words[40]; 
    char *word; 
    int wmax=0, i; 

    printf("Enter a line of text :"); 
    scanf("%79[^\n]", text); 
    for(word = strtok(text, " "); word ; word = strtok(NULL, " ")){ 
     words[wmax++] = word; 
    } 
    qsort(words, wmax, sizeof(*words), cmp); 
    for(i=0;i<wmax;++i) 
     printf("%s\n", words[i]); 

    return 0; 
}