如何按字母顺序对字符串中的单词进行排序

时间:2014-04-07 16:27:20

标签: c alphabetical-sort

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

#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); 
}

1 个答案:

答案 0 :(得分: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;
}