字符串初始化
我习惯用最简单的方式,省略大括号的那种。
char str [] = "i am jianwei";
然后今天总结的第一个是—— strlen 函数
初学者很容易混淆字符串的长度和字符串数组的大小,例如:
char str [100] = "i love c yuyan";
上边代码定义一个可以存放 100 个字符的数组,但 str 字符串只被初始化为包含 14 个字符的长度。
因此,sizeof(str) 的结果是 100,而 strlen(str) 的结果则是 14。
举个栗子,贴上代码:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100] ="i love c yuyan";
printf("%d\n", strlen(str));
printf("%d\n", sizeof(str));
}
运行结果:
补充一点:
strlen 长度 : 只是字符个数,不包含\0
sizeof 尺寸 : 尺寸,大小,包含\0
然后总结今天的第二个函数——strcpy函数
strcpy 函数用于拷贝字符串,包含最后的结束符 '\0'。
为了避免溢出,必须确保用于存放的数组长度足以容纳待拷贝的字符串(注意:长度需要包含结束符 '\0')
举个栗子,贴上代码。
#include<stdio.h>
#include<string.h>
int main()
{
char str1[] = "i am jianwei ";
char str2[] = "i am a girl";
strcpy (str1, str2);
printf ("%s\n", str1);
}
原来strcpy函数在复制的过程中,把字符串结尾的\0也复制了过去
编译器看到\0就认为字符串结束了,OK,就是这样子。
然后!敲黑板重点来了!
这种将长字符串赋值给短字符串是不允许的,会造成内存溢出,访问不该访问的地方,造成无法预料的结果。
因此,复制之前,确保目的字符串 能够 保存 源字符串。
#include<stdio.h>
#include<string.h>
int main()
{
char d[]="123"; char s[]="123456789";
strcpy(d,s);
printf("%s\n",d);
printf("%s",s);
}
定义d
1 | 2 | 3 | \0 |
d |
定义s
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | \0 |
s |
此时,strcpy将s复制到d之中,有:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
\0 |
d | s |
在不同的编译器环境中 有的可能报错 有的可能正常复制 所以这种做法很危险!
然后今天的第三个函数——strncpy函数
为了保证复制 过程中的安全,有了strncpy函数:
这个函数很有意思 前排温馨提示:
为了使该函数更“安全”,建议使用 dest[sizeof(dest) - 1] = '\0'; 语句确保目标字符串是以 '\0' 结尾。(dest解释如下)
dest | 指向存放字符串的目标数组 |
举个栗子 贴上代码
#include<stdio.h>
#include<string.h>
int main()
{
char str1[] = "To be or not to be";
char str2[40];
strncpy(str2,str1,5);
str2[5] = '\0';
printf("%s\n", str2);
}
这个函数有意思,为什么呢,因为在复制的时候不会自动在字符串末尾追加\0,
所以我们在最后的一个长度要 str2[5] = '\0';
然后今天的第四个函数——strcat函数
#include<stdio.h>
#include<string.h>
int main()
{
char str1 [100]="i am jianwei ";//最好定义一下长度 否则自动计算可能长度不够
char str2 []="i am a girl";
strcat(str1, str2);
printf("%s", str1);
}
然后今天的第五个函数——strncat函数
strncat函数,类似于strcpy,区别在于strcpy需要自己追加\0,而strncat总是自动追加结束符\0 。
举个栗子
#include<stdio.h>
#include<string.h>
int main()
{
char str1 [100] = "i like";
char str2 [] = "c yuyan";
strcat(str1, " ");
strncat(str1, str2, 7);
printf("%s", str1);
}
运算结果
然后今天的第六个函数——strcmp函数
函数原型:
#include <string.h>
...
int strcmp(const char *s1, const char *s2);
参数解析:
参数 | 含义 |
s1 | 指向待比较的字符串 1 |
s2 | 指向待比较的字符串 2 |
返回值:
返回一个整数表示两个字符串的大小关系:
返回值 | 含义 |
< 0 | 字符串 1 的字符小于字符串 2 对应位置的字符 |
0 | 两个字符串的内容完全一致 |
> 0 | 字符串 1 的字符大于字符串 2 对应位置的字符 |
举个栗子
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10] = "FishC.com";
char str2[20] = "FishC.com";
if (!strcmp(str1, str2))
{
printf("两个字符串完全一致!\n");
}
else
{
printf("两个字符串不同!\n");
}
return 0;
}
运算结果
然后今天的最后一个函数了——strncmp函数
函数原型:
#include <string.h>
...
int strncmp(const char *s1, const char *s2, size_t n);
参数解析:
参数 | 含义 |
s1 | 指向待比较的字符串 1 |
s2 | 指向待比较的字符串 2 |
n | 指定待比较的字符数 |
返回值:
返回一个整数表示两个字符串的关系:
返回值 | 含义 |
< 0 | 字符串 1 的字符小于字符串 2 对应位置的字符 |
0 | 两个字符串的内容完全一致 |
> 0 | 字符串 1 的字符大于字符串 2 对应位置的字符 |