#include<string.h>
长度 strlen(str) string length
赋值 strcpy(str2,str1) string copy
连接 strcat(str2,str1) string combination
比较 strcmp(str1,str2) string comparison → 比较ASCII码
问题:请编程实现按奥运会参赛国国名在字典中的顺序对其入场次序进行排序。假设参赛国不超过150个。
1 #include<stdio.h> 2 #include<string.h> 3 #define MAX_LEN 10 /*字符串最大长度*/ 4 #define N 150 /*字符串个数*/ 5 void SortString(char str[][MAX_LEN],int n); 6 int main(void) 7 { 8 int i,n; 9 char name[N]{MAX_LEN}; /*定义二维字符数组*/ 10 printf("How many countries?"); 11 scanf("%d",&n); 12 getchar(); /*读走输入缓冲区中的回车符*/ 13 printf("Input their names: "); 14 for(i=0;i<n;i++) 15 { 16 gets(name[i]); /*输入n个字符串*/ 17 } 18 SortString(name,n); /*字符串按字典顺序排序*/ 19 printf("Sorted results: "); 20 for(i=0;i<n;i++) 21 { 22 puts(names[i]); 23 } 24 return 0; 25 } 26 27 void SortString(char str[][MAX_LEN],int n) 28 { 29 int i,j; 30 char temp[MAX_LEN]; 31 for(i=0;i<n-1;i++) 32 { 33 for(j=i+1;j<n;j++) 34 { 35 if(strcmp(str[j],str[i])<0) 36 { 37 strcpy(temp,str[i]); 38 strcpy(str[i],str[j]); 39 strcpy(str[j],temp); 40 } 41 } 42 } 43 }
#include<stdio.h> #define N 80 unsigned int MyStrlen(const char *pStr); main() { char str[N]; printf("Input a string:"); gets(str); printf("The length of the string is:%u ",MyStrlen(str)); } unsigned int MyStrlen(const char *pStr) { unsigned int len=0; for(;*pStr!='