字符串函数strncpy/strncat/strncmp

(二)字符函数

2.1 strncpy - 字符串拷贝,可以和strcpy进行比较学习;(区别是strncpy 拷贝的长度有限制)

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.

destination

Pointer to the destination array where the content is to be copied.

source

C string to be copied.

num

Maximum number of characters to be copied from source.
size_t is an unsigned integral type.(拷贝num个字符从源字符(source)到目标空间(destination),如果源字符串的长度小于num,就在拷贝完成以后,追加0,直到num个);

Return Valuedestination is returned.

#include<string.h>

int main()
{
	char arr1[30] = "***********";
	char arr2[] = "Good day";
	printf("%s", strncpy(arr1, arr2, 4));
	return 0;
}

2.2 strncat - 和“strcat"比较使用;

char * strncat ( char * destination, const char * source, size_t num );

Append characters from string

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.(如果num超过了source的字符个数,则不会补0,只会追加source里面存在的字符);

int main()
{
	char arr1[20] = "**********";
	char arr2[] = "good";
	printf("%s", strncat(arr1, arr2, 3));
	return 0;
}

2.3 strncmp - Compare characters of two strings,和strcmp比较学习;

int strncmp ( const char * str1, const char * str2, size_t num );

Compares up to num characters of the C string str1 to those of the C string str2.(最多比较num个字符)
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ, until a terminating null-character is reached, or until num characters match in both strings, whichever happens first.

#include <stdio.h>
#include <string.h>

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)
        {
            printf("found %s\n", str[n]);
        }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值