当前位置: 移动技术网 > IT编程>开发语言>Java > C语言 连接字符串

C语言 连接字符串

2020年07月13日  | 移动技术网IT编程  | 我要评论
头文件 原型 说明 返回值
#include<stdio.h> char *strcat(char *s1, const char *s2) 将s2指向的字符串连接到s1指向的数组末尾。若s1和s2指向的内存空间重叠,则作未定义处理。 返回s1的值。
#include <stdio.h>
#include <string.h>

int main(void){
	char str[] = "vv";
	char *p = "cat";
	
	printf("连接后的字符串为:%s", strcat(str, p));
	
	return 0;
}

运行结果:
在这里插入图片描述

strcat函数实现:

char *strcat(char *s1, const char *s2){
	char *tmp = s1;
	
	while(*s1){
		s1++;
	}
	
	while(*s1++ = *s2++){
		
	};
	
	return tmp;
}

strncat函数控制连接字符串的个数
头文件 原型 说明 返回值
#include<stdio.h> char *strncat(char *s1, const char *s2, size_t n) 将s2指向的字符串连接到s1指向的数组末尾。若s2的长度大于n则截断超出部分。若s1和s2指向的内存空间重叠,则作未定义处理。 返回s1的值。
#include <stdio.h>
#include <string.h>

int main(void){
	char str[] = "vv";
	char *p = "cat";
	
	printf("连接后的字符串为:%s", strncat(str, p, 3));
	
	return 0;
}

运行结果:
在这里插入图片描述

strncat函数实现:

char *strncat(char *s1, const char *s2, size_t n){
	char *tmp = s1;
	
	while (*s1){
		s1++;
	}
	
	while (n--){
		if (!(*s1++ = *s2++)){
			break;
		}
	}
	
	*s1 = '\0';
	
	return tmp;
}

本文地址:https://blog.csdn.net/qq_44989881/article/details/107262463

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网