char s[3][4]; //3行 4列 的一个 char类型二维数组
//一个存放了 3个 char[4]这种类型的一维数组
输入用gets(s)
char s[10];
gets(s);
字符串处理函数
在C函数库中提供了一些用来处理字符串的函数,使用方便。几乎所有版本的C语言编译系统都提供这些函数。下面介绍几种常用的函数。
strlen函数(数组长度)
1 #include<stdio.h>
2
3 int main(void)
4 {
5 char s[10] = "hello";
6 int i = 0;
7 int count = 0;
8 while(s[i] != '\0')
9 {
10 ++count;
11 ++i;
12 }
13 printf("%d\n", count);
14 return 0;
15 }
等价于
strlen(s);
注:strlen函数只计算有效字符,sizeof函数吧‘\0’计算在内。
strcpy函数(复制)
1 #include<stdio.h>
2
3 int main(void)
4 {
5 char s1[100];
6 char s2[100];
7 int i = 0;
8 gets(s1);
9 while(s1[i] != '\0')
10 {
11 s2[i] = s1[i];
12 ++i;
13 }
14 s2[i] = '\0';
15 puts(s2);
16 return 0;
17 }
等价于
strcpy(目标数组,源数组);
strcat函数(拼接)
1 #include<stdio.h>
2 #include<string.h>
3 int main(void)
4 {
5 char s1[100] = "Hello,";
6 char s2[100] = "World!";
7 int j = 0;
8 int i = 0;
9 int len = strlen(s1);
10 while(s1[i] != '\0')
11 {
12 ++i;
13 }
14 while(s2[j] != '\0')
15 {
16 s1[i] = s2[j];
17 ++j;
18 ++i;
19 }
20 s1[i] = '\0';
21 puts(s1);
22 return 0;
23 }
等价于
strcat(目标数组,源数组);
strcmp函数(比较)
#include <stdio.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int i = 0;
while (str1[i] != 0 && (str1[i] == str2[i]) && str2[i] != 0)
{
i++;
}
int result = str1[i] - str2[i];
printf(" %d", result);
return 0;
}
等价于
strcmp(s1,s2);
练习:
从键盘输入5个字符串,找出最大的字符串 (strcmp)
1 #include<stdio.h>
2 #include<string.h>
3
4 int main(void)
5 {
6 char s[][10] = {"Hello","World","China","America"};
7 char max[10] ;
8 int rows = sizeof(s) / sizeof(s[0]);
9 strcpy(max,s[0]);
10 int i = 0;
11 for(i = 1; i < rows;++i)
12 {
13
14 if(strcmp(s[i] , max) > 0)
15 {
16 strcpy(max, s[i]);
17 }
18 }
19 puts(max);
20 return 0;
21 }
2、查找
1 #include<stdio.h>
2 #include<string.h>
3 int main(void)
4 {
5 char s[][10] = {"Hello","World","China","America"};
6 char room[10];
7 char m[100] = "Hello";
8 int rows = sizeof(s) / sizeof(s[0]);
9 int i = 0;
10 int j = 0;
11 for(j = rows - 1;j > 0;--j)
12 {
13 for(i = 0 ; i < j;++i)
14 {
15 if(strcmp(s[i],s[i + 1]) > 0)
16 {
17 strcpy(room , s[i]);
18 strcpy(s[i], s[ i + 1]);
19 strcpy(s[i + 1], room);
20 }
21 }
22 }
23 int begin = 0;
24 int end = rows - 1;
25 int mid;
26
27 while(begin <= end)
28 {
29
30 mid = (begin + end) / 2;
31 if(strcmp(s[mid],m) > 0)
32 {
33 end = mid - 1;
34 }
35 else if( strcmp(s[mid],m) < 0)
36 {
37 begin = mid +1;
38 }
39 else
40 break;
41 }
42
43 if(begin <= end)
44 {
45 printf("%d\n",mid);
46 }
47 else
48 {
49 printf("no\n");
50 }
51 return 0 ;
52 }