按字典顺序对字符串进行排序
#include <stdio.h> #include <string.h> int main() { char str[5][50], temp[50]; printf("Enter 5 words: "); // Getting strings input for (int i = 0; i < 5; ++i) { fgets(str[i], sizeof(str[i]), stdin); } // storing strings in the lexicographical order for (int i = 0; i < 5; ++i) { for (int j = i + 1; j < 5; ++j) { // swapping strings if they are not in the lexicographical order if (strcmp(str[i], str[j]) > 0) { strcpy(temp, str[i]); strcpy(str[i], str[j]); strcpy(str[j], temp); } } } printf("\nIn the lexicographical order: \n"); for (int i = 0; i < 5; ++i) { fputs(str[i], stdout); } return 0; }
输出
Enter 5 words: R programming JavaScript Java C programming C++ programming In the lexicographical order: C programming C++ programming Java JavaScript R programming
为了解决这个程序,创建了一个名为
str 的二维字符串。字符串最多可以容纳
5
个字符串,每个字符串最多可以有
50
个字符(包括
null
字符)。
在程序中,我们用到了两个库函数:
strcmp()-比较字符串
strcpy()-复制字符串
这些函数用于比较字符串并按正确顺序对它们进行排序。