字符函数第三弹:C语言中常见字符函数的用法解析之长度受限制的字符串函数

长度受限制的字符串函数

1. 引出

长度不受限制的字符串函数长度受限制的字符串函数
strcpystrncpy
strcatstrncat
strcmpstrncmp

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; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值