文档详情

C语言程序设计 任正云 第7章数组新.ppt

发布:2015-12-14约1.52万字共44页下载文档
文本预览下载声明
strcat(字符数组名1,字符数组名2) string.h 将字符数组2 连接到字符数组1的后面,连接时 自动取消字符数组1后面的结束标志; 结果存放到字符数组1中,函数返回值是字符数组1 的首地址; 字符数组1要有足够的空间存放结果 ; strcpy(字符数组1,字符串2) string.h 将 字符串2 复制到字符数组1,包括 \0; 字符数组1 必须有足够的空间存放结果; 字符串2可以是数组名。 可以将字符串2前面的若干个字符赋值到字符数组1中去。 不能用赋值语句将一个字符串赋值给字符数组 例 char str1[20], str2[20]; str1={Hello! }; (?) str2=str1; (?) 例: strcpy 和 strcat #include string.h #include stdio.h main() { char destination[25]; char blank[] = , c[]= C++, turbo[] = Turbo; strcpy(destination, turbo); strcat(destination, blank); strcat(destination, c); printf(%s\n, destination); } Turbo C++ T r b o C + + 0 1 2 3 4 5 6 7 8 9 u \0 24 ……. T r b o 0 1 2 3 4 5 6 7 8 9 u \0 24 ……. ……. T r b o \0 0 1 2 3 4 5 6 7 8 9 u 24 ……. …... strcmp(字符串1,字符串2) string.h 用字符的 ASCII 值逐个对应比较 字符串1 与 字符串2 字符的大小 (left-to-right); if 字符串1 字符串2 , 返回 0 ; if 字符串1==字符串2 ,返回=0 ; if 字符串1 字符串2 ,返回0 ; 不能用 == 去直接比较两个字符串的大小. strlen(字符数组) string.h 返回字符串的长度 ; 函数的值是字符串的实际长度 ,不包括 ‘\0’. 例 strlen(s) 的结果: (1)char s[10]={A, \0, B, C, \0, D}; (2)char s[ ]=\t\b\\\0will\n; (3)char s[ ]=\x69\072\n; 结果:1 3 1 #include string.h #include stdio.h main() { char str1[] = Hello! , str2[] = How are you? ,str[20]; int len1,len2,len3; len1=strlen(str1); len2=strlen(str2); if(strcmp(str1, str2)0) { strcpy(str,str1); strcat(str,str2); } else if (strcmp(str1, str2)0) { strcpy(str,str2); strcat(str,str1); } else strcpy(str,str1); len3=strlen(str); puts(str); printf( Len1=%d,Len2=%d,Len3=%d\n ,len1,len2,len3); } How are you?Hello! Len1=6,Len2=12,Len3=18 例 : strcmp 和 strlen Y 0 Y 1 1 Y 1 N 0 1 N 0 Y 1 2 N 1 N 1 2 Y 1 N 0 2 N 0 Y 1 3 Y 1 N 0 3 N 0 Y 1 4 N 1 N 1 4 N 1 N 1 4 N 1 N 1 4 例 : 输入一行字符,统计单词的个数,单词之间用空格隔开。 当前字符 ==空格 Y N 未出现新单词,使 word=0,num 不累加。 前一字符为空格 (word==0),新单词出现, 使word=1,num++ 前一字符为非空格(word==1),新单词未出 现, num 不累加 例 输入: I
显示全部
相似文档