【原创】字符串处理函数 - str*和sizeof
涉及函数如下:
strcat strcpy strlen strcmp strlwr strupr 关键字sizeof
代码如下(字符数组):
<span style="font-size:18px;">#include "stdafx.h"
#include <string.h>
#include <limits.h>
int main(int argc, char* argv[])
{
char str1[] = "I am Geng.";
char str2[] = "I love China!";
char str3[CHAR_MAX] = "\0";
//在此编译环境下CHAR_MAX = 127, CHAR_MIN = -128
printf("CHAR_MAX = %d, CHAR_MIN = %d\n",
CHAR_MAX, CHAR_MIN);
printf("%d\n",strcmp(str1,str2));
printf("str1's length %d, str2's length %d\n",
strlen(str1),strlen(str2)); //strlen 求得的字节数不包括\0
printf("str1's length %d, str2's length %d\n",
sizeof(str1),sizeof(str2)); //sizeof 求得的字节数包括\0
strcpy(str3, str2);
printf("%d\n",strcmp(str3,str2));
printf("str3's length %d, str2's length %d\n\n",
strlen(str3),strlen(str2));
printf("++ 小写变大写 ++\n");
printf("%s\n", strupr(str1));
printf("%s\n", strupr(str2));
printf("++ 大写变小写 ++\n");
printf("%s\n", strlwr(str1));
printf("%s\n", strlwr(str2));
return 0;
}</span>
<span style="font-size:18px;">/* 输出结果如下
CHAR_MAX = 127, CHAR_MIN = -128
-1
str1's length 10, str2's length 13
str1's length 11, str2's length 14
0
str3's length 13, str2's length 13
++ 小写变大写 ++
I AM GENG.
I LOVE CHINA!
++ 大写变小写 ++
i am geng.
i love china!
*/
</span>
对比代码(字符指针):
<span style="font-size:18px;">#include "stdafx.h"
#include <string.h>
#include <limits.h>
int main(int argc, char* argv[])
{
char *str1 = "I am Geng.";
char *str2 = "I love China!";
char str3[CHAR_MAX] = "\0";
char *pstr3 = str3;
printf("CHAR_MAX = %d, CHAR_MIN = %d\n",
CHAR_MAX, CHAR_MIN);
printf("%d\n",strcmp(str1,str2));
printf("str1's length %d, str2's length %d\n",
strlen(str1),strlen(str2)); //strlen 求得的字节数不包括\0
printf("str1's length %d, str2's length %d\n",
sizeof(str1),sizeof(str2)); //sizeof 求得的字节数包括\0
strcpy(str3, str2);
printf("%d\n",strcmp(str3,str2));
printf("str3's length %d, str2's length %d\n\n",
strlen(str3),strlen(str2));
printf("str3's length %d, str2's length %d\n\n",
sizeof(str3),sizeof(str2));
//下面这两个函数中的参数不能是指针str1或str2,可以是数组str3或指针pstr3
printf("%s\n", strupr(pstr3));
printf("%s\n", strlwr(pstr3));
return 0;
}</span>
<span style="font-size:18px;">/* 输出结果
CHAR_MAX = 127, CHAR_MIN = -128
-1
str1's length 10, str2's length 13
str1's length 4, str2's length 4
0
str3's length 13, str2's length 13
str3's length 127, str2's length 4
I LOVE CHINA!
i love china!
*/</span>
原文链接:
http://blog.csdn.net/geng823/article/details/24356979