我弄清楚了如何读取字符串,但我不确定如何使用冒泡排序按字母顺序排列它们。这就是我所要走的路。我不断收到错误“段错误(核心已转储)”。
#include <stdio.h>
#include <string.h>
#define NUM 25 /* number of strings */
#define LEN 1000 /* max length of each string */
main()
{
char Strings[NUM][LEN];
int i, j;
char tempValue;
printf("Please enter %d strings, one per line:\n", NUM);
for(i=0; i<NUM-1; i++)
{
fgets(Strings[i], LEN-2, stdin);
}
for(i=0; i<NUM-1; i++)
{
for(j=0; j<LEN-2; j++)
{
if(Strings[i][j] < Strings[i+1][j])
{
tempValue = Strings[i][j];
Strings[i][j] = Strings[i + 1][j];
Strings[i + 1][j] = tempValue;
}
}
}
}
最佳答案
使用strcmp
if(strcmp(Strings[i], Strings[i+1]) > 0)
{
//swap elements
}
它基本上会比较字符串中的字符,首先比较不匹配的字符对,如果传递给函数的第一个字符串具有更大的值,它将返回 1。
关于c - 尝试编写一个 C 程序来按字母顺序对二维数组中的 25 个单词进行冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28506880/