2014 全志科技校园招聘笔试题-------编程:
题目:给定字符串''just do it !'',将其转化为大写"JUST DO IT!"
方法一:
/* * * 给定一组字符串"just do it!",将其变成全部大写"JUST DO IT!" * 方法一:判断字符串范围,对 >=‘a’ && <='z' 的字符串进行转换,即 += 'A'-'a' */ #include <stdio.h> #include <string.h> #define STR_CHANGE 'A'-'a' void main() { int i=0; int str_length=0; /* * 使用字符数组的方法保存字符串,如果使用字符指针的形式(如下),程序会出错 * 因为,char *string形式的字符串是只读的,不允许对字符串的字符进行修改 * (只能修改指针变量str的值,使其指向其它字符串) * char *str="just do it!"; */ char str[20]="just do it!"; printf("before:%s\n",str); str_length=strlen(str); for(i=0;i<str_length;i++) { printf("before: ASCII is %3ld char is %c ",str[i],str[i]); //为了突出比较结果转换前打印出ASCII码值和对应字符 if(str[i] >= 'a' && str[i] <= 'z') { str[i] += STR_CHANGE; } printf("\tafter: ASCII is %3ld char is %c\n",str[i],str[i]); //为了突出比较结果转换后打印出ASCII码值和对应字符 } printf("after:%s\n",str); }
方法二:
/* * * 给定一组字符串"just do it!",将其变成全部大写"JUST DO IT!" * 方法二:使用函数toupper 引用头文件 ctype.h */ #include <stdio.h> #include <string.h> #include <ctype.h> void main() { int i=0; int str_length=0; char str[20]="just do it!"; printf("before:%s\n",str); str_length=strlen(str); for(i=0;i<str_length;i++) { printf("before: ASCII is %3ld char is %c ",str[i],str[i]); //为了突出比较结果转换前打印出ASCII码值和对应字符 if(str[i] >= 'a' && str[i] <= 'z') { str[i] = toupper(str[i]); } printf("\tafter: ASCII is %3ld char is %c\n",str[i],str[i]); //为了突出比较结果转换后打印出ASCII码值和对应字符 } printf("after:%s\n",str); } /* * 附录: * ctype.h 中 toupper()函数具体方法 * int toupper(int char) * { * return char+'A'-'a'; * } * * * ctype.h 中 tolower()函数具体方法 * int tolower(int char) * { * return char+'a'-'A'; * } */
运行结果:
before:just do it! before: ASCII is 106 char is j after: ASCII is 74 char is J before: ASCII is 117 char is u after: ASCII is 85 char is U before: ASCII is 115 char is s after: ASCII is 83 char is S before: ASCII is 116 char is t after: ASCII is 84 char is T before: ASCII is 32 char is after: ASCII is 32 char is before: ASCII is 100 char is d after: ASCII is 68 char is D before: ASCII is 111 char is o after: ASCII is 79 char is O before: ASCII is 32 char is after: ASCII is 32 char is before: ASCII is 105 char is i after: ASCII is 73 char is I before: ASCII is 116 char is t after: ASCII is 84 char is T before: ASCII is 33 char is ! after: ASCII is 33 char is ! after:JUST DO IT!
方法三:
使用strupr函数
/* * * 给定一组字符串"just do it!",将其变成全部大写"JUST DO IT!" * 方法三:使用函数strupr 引用头文件 string.h */ #include <stdio.h> #include <string.h> #include <ctype.h> void main() { char str[20]="just do it!"; printf("before:%s\n",str); printf("change to upper :%s\n",strupr(str)); printf("change to lower :%s\n",strlwr(str)); printf("after:%s\n",str); }