本章需要掌握:
- 1、定义数组长度必须固定,定义数值数组两种方式int a[10]; 或 int a[10] = {0,0,0};
- 2、定义字符数组的三种形式,字符数组以’\o’结尾
- 3、scanf(“%s”,arr)、strlen(c)、strcat(c,d)加、strcpy(c,d)赋值给c、strcmp(c,d)比较-1/0/1
- 4、注:四个函数在<string.h>库
1、数组定义
1 2 3 4 5 6 7 8 9 10 11 12
| #include <stdio.h>
int main() { int a[10]; int b[10]={1,2,3,4,5,6,7}; char c[10]; char d[10]={'a','b','c'}; printf("%d\n",b[4]); printf("%c\n",d[2]); }
|
2、字符数组
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <stdio.h>
int main() { char a[10]; scanf("%s",a); char b[10]="hello"; char c[10]={'h','e','l','l','o'};
printf("%s",a); printf("%d\n",b[1]); printf("%c\n",c[9]); return 0; }
|
3、gets、puts
1 2 3 4 5 6 7 8 9
|
char c[20]; gets(c); puts(c)
scanf("%s",&c); printf("%s",c);
|
4、str系列
1 2 3 4 5
| #include <string.h> strlen(c); strcat(c,d); strcpy(d,c); strcmp(c,d);
|
🌺5、OJ作业
网站:http://oj.lgwenda.com/
1、统计数字(Statistics)
描述:输入N个数(N小于等于100),输出数字2的出现次数;
输入:输入的格式是两行。第一行输入要输的元素个数,比如5;第二行输入 1 2 2 3 2,那么输出结果为3,因为2出现了3次。
输出:统计数字2出现的次数
🌺🌺🌺题解ヾ(^▽^)ゞ🌼🌼🌼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <stdio.h>
int main() { int element_count; int arr[100]; scanf("%d",&element_count); int i; for(i=0;i<element_count;i++) { scanf("%d",&arr[i]); }
int count=0; for(i=0;i<element_count;i++) { if(arr[i]==2) { count++; } } printf("%d\n",count); return 0; }
|
2、字符串翻转(String-Reverse)
描述:读取一个字符串,字符串可能含有空格,将字符串逆转,原来的字符串与逆转后字符串相同,输出0,原字符串小于逆转后字符串输出-1,大于逆转后字符串输出1。例如输入 hello,逆转后的字符串为 olleh,因为hello 小于 olleh,所以输出-1(注:strcmp返回的是正负值而不是+1or-1)
输入:输入一个字符串,例如 hello,当然输入的字符串也可能是 how are you,含有空格的字符串
输出:输出是一个整型数,如果输入的字符串是hello,那么输出的整型数为-1
🌺🌺🌺题解ヾ(^▽^)ゞ🌼🌼🌼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #include <stdio.h> #include <string.h>
int main() { char c[100]; char d[100]={0}; scanf("%s",&c); int i,j; for(i=0,j= strlen(c)-1;i< strlen(c);i++,j--) { d[j]=c[i]; } int result=strcmp(c,d); if(result>0) { printf("%d\n",1); } else if(result<0) { printf("%d\n",-1); } else{ printf("%d\n",0); } return 0; }
|