比较单个字符可使用关系运算符(<、>、=),但使用字符串不能直接使用关系运算符,应使用字符串处理函数,使用时必须要在程序的开头加入头文件<string.h>
【字符串处理函数】
strlen(字符串) 字符串的长度
.strcmp(字符串1,字符串2) 字符串的比较
strcpy(目的字符串,源字符串) 相当于“=”
strcat(目的字符串,源字符串) 字符串的连接
提示:目的字符必须足够大
例:请编程实现奥运会参赛国名在字典中的顺序对其入场顺序排序,不超过150个国家
#include<stdio.h>
#include<string.h>
#define MAX 10
#define N 150
void SortString(char str[][MAX],int n);
int main()
{
int i,n;
char name[N][MAX];
printf("how many countries?\n");
scanf("%d",&n);
getchar();
printf("please input their name:\n");
for(i=0;i<n;i++)
{
scanf("%s",&name[i]);
}
SortString(name,n);
printf("sorted results:\n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
return 0;
}
//函数功能:将字符串按顺序排列
void SortString(char str[][MAX],int n)
{
int i,j;
char temp[MAX];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(str[j],str[i])<0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
}