字符数组
定义
初始化 : 单个字符初始化 用字符串常量初始化
输入输出 : %s 不能够获得带有分隔符的串
存储特点 结束标记(\0)
#include<stdio.h>
#include<stdlib.h>#define N 32int main(){char str[N] = {'a','b','c'};chr str0[N],str1[N],str2[N];int i;//(F) str = "hello"报错 str是常量//gets(str);//warning 最好不好使用gets 危险性在于不检查缓冲区的大小,导致数组越界而没有报错。 //puts(str);scanf("%s%s%s",str0,str1,str2);printf("%s\n%s\n%s\n",str0,str1,str2);for(i= 0;i<N,i++){printf("%c ",str[i]);}exit(0);
}
string 库 man strcpy
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 32
#define STRSIZE 32
/*
strlen & sizeof
strcpy & strncpy
strcat & strncat
strcmp & strncmp
*/int main(){char str[32] = "hello\0abc";strcpy(str,"abcde");//strcpy没有溢出警告puts(str);char str[STRSIZE] = "hello";strncpy(str,"abcde",STRSIZE-1);//可以防止越界strcat(str," ");strcat(str,"world!");strncat(str," ",STRSIZE);strncat(str," ",STRSIZE);char str2[STRSIZE]="hello";char str3[STRSIZE]="world";printf("%d\n",strcmp(str2,str3));//strcmp返回值ascall码差值 str2-str3 返回负 0 正printf("%d\n"strcnmp(str2,str3,5));//比较前n个printf("%d\n",strlen(str)); //以\0 为结束标记 5printf("%d\n",sizeof(str)); //实际的占用字节个数 6exit(0);
}
单词计数
#include<stdio.h>
#include<stdlib.h>int main(){char str[128];int i,count = 0,flag = 0;gets(str);for(i = 0;str[i] !='0\';i++){if (str[i] ==' ')flag = 0;elseif(flag == 0){count++;flag = 1;}}exit(0);
}
多维数组