Pregunta

Whats the easiest way to sort the words in a string in aplhabetical order? I made the following code but it does not work for smaller words and it also prints a lot of garbage values.Could you tell me why?

#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); 
}
¿Fue útil?

Solución

#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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top