5. C language uses functions to realize string copying (does not use strcpy() function) (contains multiple methods)

5. C language uses functions to realize string copying (does not use strcpy() function) (contains multiple methods)

—————————————————————————————
(1) The first method: use array subscript access (recommended)

#include<stdio.h>

//第一种方法:使用数组下标访问
void Copy1(char*des,char*src)//des是目标,src是源字符串
{
    
    
	int i;
	for(i=0;src[i]!='\0';i++)//当src[i]出现'\0'时,代表字符串遍历结束
	{
    
    
		des[i]=src[i];//给des[i]赋值
	}
	des[i]='\0';//给复制好的des[i]的结尾加上'\0',代表字符串的结束
}
int main()
{
    
    
	char arr[10]="abcdefg";
	char brr[10];
	Copy1(brr,arr);//调用函数1
	printf("brr是%s",brr);//输出复制好的字符串数组brr
	printf("\n");
	return 0;
}

Execution resultInsert picture description here
—————————————————————————————
(2) The second method: using pointer dereference to access the array (not quite recommend)

#include<stdio.h>

//第一种方法:使用指针解引用访问(原理:利用p[i]等价于*(p+i))
void Copy2(char*des,char*src)//des是目标,src是源字符串
{
    
    
	int i;
	for (i = 0; *(src+i)!='\0'; i++)//当src出现'\0'时,代表字符串遍历结束
	{
    
    
		*(des+i)=*(src+i);//给des赋值
	}
	*(des+i)='\0';//给复制好的des的结尾加上'\0',代表字符串的结束
}
int main()
{
    
    
	char arr[10]="abcdefg";
	char brr[10];
	Copy2(brr,arr);//调用函数2
	printf("brr是%s",brr);//输出复制好的字符串数组brr
	printf("\n");
	return 0;
}

Results of the
Insert picture description here

—————————————————————————————
(3) The third method: use pointer operations, move pointers to access array elements (very very important )

#include<stdio.h>

void Copy3(char* des, char* src)//利用指针操作,指针自行移动,*******非常非常非常重要********。
{
    
    
	/*while (*src != '\0')
	{
		*des = *src;
		src++;
		des++;
	}*/
	for (; *src != '\0'; src++, des++)//与上面注释代码二选一即可
	{
    
    
		*des = *src;
	}
	*des = '\0';
} 

int main()
{
    
    
	char arr[10]="abcdefg";
	char brr[10];
	Copy3(brr,arr);//调用函数3
	printf("brr是%s",brr);//输出复制好的字符串数组brr
	printf("\n");
	return 0;
}

Execution result
Insert picture description here
—————————————————————————————
(4) The fourth type: one line of code (not recommended)

#include<stdio.h>

void Copy4(char* des, char* src)
{
    
    
	while (*des++ = *src++);//经典代码,不建议使用//
	//技巧一:int i = 10; int j = i++;
	//技巧二:int i=10;if(i)
}

int main()
{
    
    
	char arr[10]="abcdefg";
	char brr[10];
	Copy4(brr,arr);//调用函数4
	printf("brr是%s",brr);//输出复制好的字符串数组brr
	printf("\n");
	return 0;
}

Operation result
Insert picture description here
—————————————————————————————
Day4 2020-12-17 Thursday, sunny

Sometimes restless like fire, sometimes gentle like water, sometimes quiet as if living in an ivory tower, and sometimes mixed in the crowd with ease. Sometimes I cried and pierced my heart, and sometimes laughed tremblingly. Sometimes pretentious, sometimes arrogantly humble. What's wrong with this? The name of the disease is love.Insert picture description here

Guess you like

Origin blog.csdn.net/xiaoxiaoguailou/article/details/111306407