字符串函数
前面我们讲了strlen、strcat、strcpy、strcmp函数的使用和模拟实现。
hello,我是结衣。今天我们讲字符串函数strcpy、strcat、strcmp函数的限制使用。就是可以自己限制字符的使用数目。
将这些函数中间填加‘n’变为strncpy、strncat、strncmp。
strncpy函数
使用该函数可以将源字符串复制到目的字符串中,并且可以限制复制的字符个数。
格式
char * strncpy ( char * destination, const char * source, size_t num );
代码
#include <stdio.h>
#include <string.h>
int main()
{
char ch1[20] = "abc";
char ch2[] = "abcdef";
printf("%s\n", strncpy(ch1, ch2,1));//strcpy函数可以限制字符数目。
return 0;
}
strncat函数
格式和上面一样的
代码
#include <stdio.h>
#include <string.h>
int main()
{
char ch1[20] = "abc";
char ch2[] = "abcdef";
printf("%s\n", strncat(ch1, ch2, 3));//strcat函数可以限制字符数目。
return 0;
}
strncmp函数
格式
int strncmp ( const char * str1, const char * str2, size_t num );
代码
#include <stdio.h>
#include <string.h>
int main()
{
char ch1[20] = "abc";
char ch2[] = "abcd";
printf("%d\n", strncmp(ch1, ch2,4));//strcmp函数可以限制字符数目,记得用%d
return 0;
}
因为代码很简单,结衣相信大家都可以看懂的,就没有过多的解释。这篇文章注意是让大家可以了解一下。
那么就到此结束了,下次在见了。