编写一个C程序,按字母顺序对名称进行排序。此示例允许输入多个字符串或名称,并使用for循环按字母顺序对它们进行排序。if语句(if (strcmp(str[i], str[j]) > 0) )将每个字符串与其他字符串进行比较。strcpy函数会将该字符串复制到temp,然后根据结果更改它们的位置。
#include <stdio.h>
#include <string.h>
int main()
{
char str[50][50], temp[50];
int i, j, number;
printf("How many Strings you want to enter = ");
scanf("%d", &number);
printf("Please Enter String one by one\n");
for (i = 0; i <= number; i++)
{
fgets(str[i], sizeof str[i], stdin);
}
for (i = 0; i <= number; i++)
{
for (j = i + 1; j <= number; j++)
{
if (strcmp(str[i], str[j]) > 0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
printf("\n***** The Order of the Sorted Strings *****");
for (i = 0; i <= number; i++)
{
puts(str[i]);
}
return 0;
}

在此程序中,sortNamesAlphabetically函数将按字母顺序对字符串集或字符串名称进行排序。
#include <stdio.h>
#include <string.h>
char str[50][50], temp[50];
int i, j, number;
void sortNamesAlphabetically()
{
for (i = 0; i <= number; i++)
{
for (j = i + 1; j <= number; j++)
{
if (strcmp(str[i], str[j]) > 0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
}
int main()
{
printf("How many Words you want to enter = ");
scanf("%d", &number);
printf("Please Enter one by one\n");
for (i = 0; i <= number; i++)
{
fgets(str[i], sizeof str[i], stdin);
}
sortNamesAlphabetically();
printf("\n**********");
for (i = 0; i <= number; i++)
{
puts(str[i]);
}
return 0;
}
How many Words you want to enter = 6
Please Enter one by one
usa
india
uk
japan
china
australia
**********
australia
china
india
japan
uk
usa