谭浩强C程序设计(第三版)课件_第7章_数组.ppt
文本预览下载声明
比较的结果由函数值带回 (1) 如果字符串1=字符串2,函数值为0。 (2) 如果字符串1字符串2,函数值为一正整数。 (3) 如果字符串1字符串2,函数值为一负整数。 注意:对两个字符串比较,不能用以下形式: if(str1str2) printf(″yes″); 而只能用 if(strcmp(str1,str2)0) printf(″yes″); 6. strlen函数 其一般形式为:strlen (字符数组) strlen是测试字符串长度的函数。函数的值为字符串中的实际长度(不包括′\0′在内)。 例如:char str[10]={″China″}; printf(″%d″,strlen(str)); 输出结果不是10,也不是6,而是5。也可以直接测试字符串常量的长度,如strlen(″China″); 7. strlwr函数 其一般形式为:strlwr (字符串) strlwr函数的作用是将字符串中大写字母换成小写字母。 8. strupr函数 其一般形式为:strupr (字符串) strupr函数的作用是将字符串中小写字母换成大写字母。 例7 .8 输入一行字符,统计其中有多少个单词,单 词之间用空格分隔开。 7.3.7字符数组应用举例 程序如下: #include stdio.h void main() { char string[81]; int i,num=0,word=0; char c; gets(string); for (i=0;(c=string[i])!=′\ 0′;i++) if(c==′ ′) word=0; else if(word==0) { word=1; num++; } printf(″There are %d words in the line.\n″,num); } 运行情况如下: I am a boy.↙ There are 4 words in the line. 例7.9 有3个字符串,要求找出其中最大者 程序如下: #includestdio.h #includestring.h void main ( ) { char string[20]; char str[3][20]; int i; for (i=0;i3;i++) gets (str[i]); if (strcmp(str[0],str[1])0) strcpy(string,str[0]) else strcpy(string,str[1]); if (strcmp(str[2],string)0) strcpy(string,str[2]); printf(″\nthe largest string is∶ \n%s\n″,string); } 运行结果如下: CHINA↙ HOLLAND↙ AMERICA↙ ? the largest string is∶ HOLLAND 4.如果对全部元素都赋初值,则定义数组时对第一维的长度可以不指定,但第二维的长度不能省。 例如:int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};它等价于:int a[][4]={1,2,3,4,5,6,7,8,9,10,11,12}; 在定义时也可以只对部分元素赋初值而省略第一维的长度,但应分行赋初值。 例如:int a[][4]={{0,0,3},{},{0,10}}; 0 0 3 0 0 0 0 0 0 10 0 0 7.2.4二维数组程序举例 例7.4 将一个二维数组行和列元素互换,存到另一个 二维数组中。 #include stdio.h void main() { int a[2][3]={{1,2,3},{4,5,6}}; int b[3][2],i,j; printf(″array a:\n″); for (i=0;i=1;i++) { for (j=0;j=2;j++) { 例如:a= 1 2 3 1 4 4 5 6 b= 2 5 3 6 printf(″%5d″,a[i][j]); b[j][i]=a[i][j]; }
显示全部