微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c语言中strncat函数,函数原型以头文件

1、函数原型

#include <stdio.h>

char *strncat(char *s1, const char *s2, size_t n) //函数的返回值为指向char型的指针,形参为两个指针(函数间数组(字符串数组)的传递是以指向数组第一个元素的指针进行的)和正整数n。 
{
    char *tmp = s1;  // 将指针 tmp 初始化为指针 s1, 指向字符串数组str1第一个元素的指针 
    while(*s1) 
        s1++; //将指针s1由指向字符串数组第一个元素,移动到指向字符串数组末尾的null字符。 
    while(n--) //循环判断条件1,n--当n小于字符串数组str2的时候,复制n个字符就截断。 此种情况s1指针最终所指的为str1最后一个字符后面的字符,不一定是null。 
        if(!(*s1++ = *s2++))  // 循环判断条件2,当n大于str2的长度的时候, 指针s2指向字符串数组末尾的null字符时,循环终止。 此种情况,s1指针最终所指为*s2传递给*s1的null字符。 
            break;
    *s1 = '\0';  // 之所以要这么做,是应为在n < str2的情况下,s1指针指向了str1最后一个字符的后一个字符,不一定是null,因此将其赋值为null,因为字符串终止的标志是null。 
    return tmp;
}

int main(void)
{
    char str1[128] = "abcdefg";
    char str2[128] = "123456789";
    
    size_t n;
    printf("n = "); scanf("%u", &n);
    
    printf("concatenate result: %s\n", strncat(str1, str2, n));
    
    return 0;
}

 

 

2、加载strncat函数的头文件,可以直接调用strncat函数

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

int main(void)
{
    char str1[128] = "abcdefg";
    char str2[128] = "123456789";
    
    size_t n;
    printf("n = "); scanf("%u", &n);
    
    printf("concatenate result: %s\n", strncat(str1, str2, n));
    
    return 0;
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐