文档详情

C语言程序设计_谭浩强_第7章数组.ppt

发布:2017-05-04约1.79万字共48页下载文档
文本预览下载声明
§7.1 一维数组的定义和引用 main() { char a[]={h,e,l,\0,l,o,\0}; printf(%s,a); } 例 输出:hel h e l \0 l o \0 数组中有多个‘\0’时, 遇第一个结束 main() { int i; char a[5]; scanf(%s,a); for(i=0;i5;i++) printf(%d,,a[i]); } 运行情况: (1)若输入 hel , 正常 (2)若输入 hell , 正常 (3)若输入 hello , 用%s 输出时,会出现问题 h e l \0 h e l l \0 h e l l o 输入字符串长度数组维数 例 字符串输入举例 H o w \0 a r e \0 y o u ? \0 #include stdio.h main() { char a[15],b[5],c[5]; scanf(%s%s%s,a,b,c); printf(a=%s\nb=%s\nc=%s\n,a,b,c); scanf(%s,a); printf(a=%s\n,a); } 运行情况: 输入:How are you? 输出:a=How b=are c=you? 输入:How are you? 输出:a=How scanf中%s输入时,遇空格或回车结束 运行情况: 输入:How are you? 例 若准备将字符串“This is a string.”记录下来, 错误的输入语句为: (A)scanf(“%20s”,s); (B)for(k=0;k17;k++) s[k]=getchar(); (C)while((c=getchar())!=‘\n’) s[k++]=c; 常用的字符串处理函数 包含在头文件 string.h 字符串输出函数puts 格式:puts(字符数组) 功能:向显示器输出字符串(输出完,换行) 说明:字符数组必须以‘\0’结束 字符串输入函数gets 格式:gets(字符数组) 功能:从键盘输入一以回车结束的字符串放入字符数组中, 并自动加‘\0’ 说明:输入串长度应小于字符数组维数 例 #include string.h main( ) { char string[80]; printf(“Input a string:”); gets(string); puts(string); } 输入: How are you? 输出: How are you ? 字符串连接函数strcat 格式:strcat(字符数组1,字符数组2) 功能:把字符数组2连到字符数组1后面 返值:返回字符数组1的首地址 说明:?字符数组1必须足够大 ?连接前,两串均以‘\0’结束;连接后,串1的‘\0’取消, 新串最后加‘\0’ 字符串拷贝函数strcpy 格式:strcpy(字符数组1,字符串2) 功能:将字符串2,拷贝到字符数组1中去 返值:返回字符数组1的首地址 说明:?字符数组1必须足够大 ?拷贝时‘\0’一同拷贝 ?不能使用赋值语句为一个字符数组赋值 例 char str1[20],str2[20]; str1={“Hello!”}; (?) str2=str1; (?) 例 strcpy与strcat举例 #include string.h #include stdio.h void main() { char destination[25]; char blank[] = , c[]= C++, turbo[] = Turbo; strcpy(destination, turbo); strcat(destination, blank); strcat(destination, c); printf(%s\n, destination);
显示全部
相似文档