Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

c - Sort words in a string based on their vowel number

I must write a program in C that allows an user to say how many words they want to enter in a string and then I must sort those words based on their vowel number(the word with more vowels is first and the one with the least vowels is last - if two words have the same number of vowels then leave them in the order as they have appeared). For example:

string - "Aaaa Bbbbbbb B CD home Aaa BB A poke"

Sorted string - "Aaaa Aaa home poke A Bbbbbbb B CD BB"

I know how to write the first part, but for the sort part I have no idea. Can someone help me with that please?

EDIT: Currently I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#pragma warning (disable: 4996)

int main(){
    char string1[20], string2[100] = { '' };
    int N, i;
    do{
        printf("Enter the number of words you want to enter in the string: ");
        scanf("%d", &N);
        if (N < 2){
            printf("You must enter at least two words.
");
            printf("Enter the number of words you want to enter in the string: ");
            scanf("%d", &N);
        }
    } while (N < 2);

    for (i = 0; i < N; i++){
        printf("Enter a word: ");
        scanf(" %[^
]", string1);
        if (strlen(string2) == 0)
            strcpy(string2, string1);
        else {
            strcat(string2, " ");
            strcat(string2, string1);
        }
    }

    printf("%s
", string2);

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will want to create an array of structs that hold a pointer to the word and then the number of vowels in each word. Something like:

struct vowelcnt {
    char *word;
    int numvowels;
}

Then sort the array of structs (descending order based on numvowels. Then simply loop through the sorted structs outputting the word which would give you the words sorted in order of the number of vowels contained. Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...