#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define StringMax 100//定义每个字符串的最大长度
void ShowArray(char arr[][StringMax],int n)
{
for(int i=0;i<n;i++){
printf("%s\n",arr[i]);
}
}
void StringSort(char str[][StringMax],int n){
char tmp[100];
int i;
//简单冒泡排序
for(i = 0; i < n - 1; i++)
for(int j = 0; j < n - i - 1; j++)
{
if(strcmp(str[j], str[j + 1]) > 0) // 相当于前面的字符串减去后面的,具体见strcmp函数
{
strcpy(tmp, str[j]); // 使用函数strcpy
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1],tmp);
}
}
}
void main(){
char a[3][StringMax]={"tom","jack","yzb"};
ShowArray(a,3);
StringSort(a,3);
printf("排序后的字符串为:\n");
ShowArray(a,3);
}
C语言字符串排序(采用冒泡排序法)
最新推荐文章于 2024-04-18 16:46:24 发布