自己补充排序部分吧:
程序代码:
/*
http://bbs.bccn.net/thread-439943-1-1.html
题目:从键盘输入一串英文,编程统计字符串中英文单词的个数。并按出现频次升序排序显示每个单词出现的次数
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
// 数据结构
struct WordItem // 字典项目
{
char word[30]; // 单词
size_t frequency; // 出现频率
};
// 全局常数
const size_t MaxWordsNumber = 1000; // 最大单词数目
const char* seps = " .,()*%!'\"\n";
// 函数原型
void Pause(void);
void ReadWords(char* text, const char* seps, WordItem* dictionary);
void ListDictionary(const WordItem* dictionary, size_t count);
size_t FindWord(const char* word, const WordItem* dictionary, size_t count);
// 程序主入口
int main(void)
{
char text[] = "vb. To translate all the source code of a program from a high-level language into object code prior \
to execution of the program. Object code is executable machine code or a variation of machine code. \
More generally, compiling is sometimes used to describe translating any high-level symbolic description \
into a lower-level symbolic or machine-readable format. A program that performs this task is known as \
a compiler. See also compiler (definition 2), compile time, high-level language, machine code, source \
code. Compare interpret.";
WordItem* dictionary = (WordItem*) calloc(MaxWordsNumber, sizeof(WordItem));
ReadWords(text, seps, dictionary);
ListDictionary(dictionary, MaxWordsNumber);
free(dictionary);
Pause();
return EXIT_SUCCESS;
}
// 暂停程序等待按键继续
void Pause(void)
{
printf_s("\nPress any key to continue...");
_getch();
}
// 输出字典数组明细
void ListDictionary(const WordItem* dictionary, size_t count)
{
for (size_t index = 0; (index < count) && (strlen(dictionary[index].word) > 0); ++index)
{
printf_s("%s, %u\n", dictionary[index].word, dictionary[index].frequency);
}
}
// 从字符串中提取单词构造字典数组
void ReadWords(char* text, const char* seps, WordItem* dictionary)
{
char* nextToken;
char* token = strtok_s(text, seps, &nextToken);
while (token != NULL)
{
size_t index = FindWord(token, dictionary, MaxWordsNumber);
if (index < MaxWordsNumber)
{
strcpy_s(dictionary[index].word, _countof(dictionary[index].word), token);
++dictionary[index].frequency;
}
token = strtok_s(NULL, seps, &nextToken);
}
}
// 从字典数组中查找指定的单词,若存在则返回其在字典数组中的下标,否则返回末尾下标
size_t FindWord(const char* word, const WordItem* dictionary, size_t count)
{
size_t index;
for (index = 0; (index < count) && (strlen(dictionary[index].word) > 0); ++index)
{
if (strcmp(dictionary[index].word, word) == 0)
{
break;
}
}
return index;
}