字典排序:输入n个单词,相邻单词之间由1个或多个空格间隔,请按照字典顺序输出这些单词(区分大小写),要求重复的单词只输出一次。
函数:
int getIndex(char[] word,char[] dict) //查字典
int wordComp(char[] word1,char[] word2) //单词比较
int wordsort(char[10][],int n) //单词排序
备注:单词比较可以直接利用string.h头文件中strcmp()函数,该函数用来比较参数word1和word2字符串。字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的ASCII值。
参考一下
#include <stdio.h>
#include <string.h>
int getIndex(char word[], char dict[][100], int dictSize) {
for (int i = 0; i < dictSize; i++) {
if (strcmp(word, dict[i]) == 0) {
return i;
}
}
return -1;
}
int wordComp(char word1[], char word2[]) {
return strcmp(word1, word2);
}
int wordsort(char words[][100], int n) {
char dict[100][100];
int dictSize = 0;
int index;
for (int i = 0; i < n; i++) {
index = getIndex(words[i], dict, dictSize);
if (index == -1) {
strcpy(dict[dictSize], words[i]);
dictSize++;
}
}
for (int i = 0; i < dictSize - 1; i++) {
for (int j = i + 1; j < dictSize; j++) {
if (wordComp(dict[i], dict[j]) > 0) {
char temp[100];
strcpy(temp, dict[i]);
strcpy(dict[i], dict[j]);
strcpy(dict[j], temp);
}
}
}
for (int i = 0; i < dictSize; i++) {
printf("%s ", dict[i]);
}
printf("\n");
return dictSize;
}
int main() {
char words[10][100];
int n;
printf("请输入单词个数:");
scanf("%d", &n);
printf("请输入单词,以空格分隔:\n");
for (int i = 0; i < n; i++) {
scanf("%s", words[i]);
}
wordsort(words, n);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: