s****1 发帖数: 26 | 1 Please write a function that takes a string and a “FILE *” as parameters,
assuming the string consists of words separated by a single white space, and
prints into the “FILE *” the words in the string in descending order
sorted by the number of times they appear. For example an input of “a b b”
would generate output of:
b : 2
a : 1 | t*******i 发帖数: 4960 | 2 "assuming the string consists of words"
so if the string is "ab abc ab", we would print
ab 2
abc 1
right?
if "assuming the string consists of characters", it would be much easier. | S**I 发帖数: 15689 | 3 #include
#include
#include
struct StringCount{
char s[100];
int count;
};
int compare(const void * a, const void * b){
return ((*(struct StringCount *)a).count < (*(struct StringCount *)b).count);
}
void printSortedWords(char * s, FILE * file){
int size = strlen(s);
struct StringCount sc[100];
int num = 0;
char newstr[100];
int i = 0;
for(; i < size; i++){
if(s[i] != ' '){
int j = 0;
while(s[i] != ' ' && s[i] != '\0'){
newstr[j] = s[i];
i++;
j++;
}
newstr[j] = '\0';
for(j = 0; j < num; j++){
if(!strcmp(newstr, sc[j].s)){
sc[j].count++;
break;
}
}
if(j == num){
strcpy(sc[num].s, newstr);
sc[num].count = 1;
num++;
}
}
}
qsort(sc, num, sizeof(struct StringCount), compare);
for(i = 0; i < num; i++){
fprintf(file, "%s: %d\n", sc[i].s, sc[i].count);
}
}
int main (int argc, char * argv[])
{
FILE * file;
file = fopen("output.txt", "w");
printSortedWords(argv[1], file);
fclose(file);
return 0;
} |
|