avatar
HELP: C programming question# JobHunting - 待字闺中
s*1
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
avatar
t*i
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.
avatar
S*I
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;
}
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。