带有字符串功能的 C 程序,用于按字母顺序对名称进行排序。
问题
使用冒泡排序技术,按字母顺序对用户在运行时提供的名称进行排序。
解决方案
用于按字母顺序打印名称的逻辑如下 -
for (i=1; i < ITEMS; i++){
for (j=1; j <= ITEMS-i ; j++){
if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */
strcpy (dummy, string[j-1]);
strcpy (string[j-1], string[j]);
strcpy (string[j], dummy );
}
}
}例子
以下是使用字符串函数按字母顺序对名称进行排序的 C 程序 -
#define ITEMS 5
#define MAXCHAR 20
main( ){
char string[ITEMS][MAXCHAR], dummy[MAXCHAR];
int i = 0, j = 0;
/* Reading the list */
printf ("Enter names of %d items
",ITEMS);
while (i < ITEMS)
scanf ("%s", string[i++]);
/* Sorting begins */
for (i=1; i < ITEMS; i++){
for (j=1; j <= ITEMS-i ; j++){
if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */
strcpy (dummy, string[j-1]);
strcpy (string[j-1], string[j]);
strcpy (string[j], dummy );
}
}
}
printf ("
Alphabetical list
");
for (i=0; i < ITEMS ; i++)
printf ("%s
", string[i]);
}输出
当执行上述程序时,它会产生以下输出 -
Enter names of 5 items computers architecture organization microprocessor networking Alphabetical list architecture computers microprocessor networking organization
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP