字符串拷贝的三种方法

第一种拷贝方法

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>	
#include<string.h>
#include<stdlib.h>
//字符串拷贝

//第一种的实现方式
void copyString01(char *dest, char *source)
{
	//利用下标的方式进行copy
	int len = strlen(source);
	for (int i = 0; i < len; i++)
	{
		dest[i] = source[i];
	}
	dest[len] = '\0';
}

void test01()
{
	char * str = "hello world";
	char buf[1024];
	//char buf[1024] = {0};
	copyString01(buf, str);
	printf("buf=%s\n", buf);
}
int main()
{
	//test01();
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

第二种拷贝方法

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>	
#include<string.h>
#include<stdlib.h>
//字符串拷贝

//第一种的实现方式
void copyString01(char *dest, char *source)
{
	//利用下标的方式进行copy
	int len = strlen(source);
	for (int i = 0; i < len; i++)
	{
		dest[i] = source[i];
	}
	dest[len] = '\0';
}
//第二种的实现方式    一个一个解引用
void copyString02(char *dest, char *source)
{
	//利用字符串指针的方式进行拷贝
	while (*source != '\0')
	{
		*dest = *source;
		dest++;
		source++;
	}
	*dest = '\0';
}
void test02()
{
	char * str = "hello world";
	char buf[1024];
	//char buf[1024] = {0};
	copyString02(buf, str);
	printf("buf=%s\n", buf);
}
int main()
{
	//test01();
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

第三种拷贝方法

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>	
#include<string.h>
#include<stdlib.h>
//字符串拷贝

//第一种的实现方式
void copyString01(char *dest, char *source)
{
	//利用下标的方式进行copy
	int len = strlen(source);
	for (int i = 0; i < len; i++)
	{
		dest[i] = source[i];
	}
	dest[len] = '\0';
}
//第二种的实现方式    一个一个解引用
void copyString02(char *dest, char *source)
{
	//利用字符串指针的方式进行拷贝
	while (*source != '\0')
	{
		*dest = *source;
		dest++;
		source++;
	}
	*dest = '\0';
}
//第三种拷贝方式
void copyString03(char *dest, char *source)
{
	while (*dest++ = *source++)
	{

	}
}
void test03()
{
	char * str = "hello world";
	char buf[1024];
	//char buf[1024] = {0};
	//copyString02(buf, str);
	copyString03(buf, str);
	printf("buf=%s\n", buf);
}
int main()
{
	//test01();
	//test02();
	test03();
	system("pause");
	return EXIT_SUCCESS;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值