长度受限制的字符串函数
文章目录
1. 引出
长度不受限制的字符串函数 | 长度受限制的字符串函数 |
---|---|
strcpy | strncpy |
strcat | strncat |
strcmp | strncmp |
2. 头文件引用
#include <string.h>
strncpy
1. 格式
char * strncpy ( char * destination, const char * source, size_t num );
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
2. 使用
-
拷贝num个字符从源字符串到目标空间。
-
如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。
2.1 代码演示
int main()
{
char arr1[20] = "abcdefghi";
char arr2[] = "xxxx";
strncpy(arr1, arr2, 8);
return 0;
}
2.1.1 源码的实现
char * __cdecl strncpy (
char * dest,
const char * source,
size_t count
)
{
char *start = dest;
while (count && (*dest++ = *source++) != '\0') /* copy string */
count--;
if (count) /* pad out with zeroes */
while (--count)
*dest++ = '\0';
return(start);
}
strncat
1. 格式
char * strncat ( char * destination, const char * source, size_t num );
-
Appends the first num characters of source to destination, plus a terminating null-character.
-
If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.
2. 使用
2.1 用于两个字符串数
int main ()
{
char str1[20];
char str2[20];
strcpy (str1,"To be ");
strcpy (str2,"or not to be");
strncat (str1, str2, 6);
puts (str1);
return 0;
}
2.2 字符串自我追加
int main()
{
char arr1[20] = "abc";
strncat(arr1, arr1, 3);
printf("%s\n", arr1);
return 0;
}
strncmp
1. 格式
int strncmp ( const char * str1, const char * str2, size_t num );
2. 使用
比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)//比较前两个元素,相等即为0
{
printf ("found %s\n",str[n]);
}
return 0;
}