使用C語言實現字符串復制


一、概述

  案例:使用C語言編寫一個函數,來實現字符串的copy。

二、代碼示例

  

#include <iostream>

using namespace std;

/**
 * 使用數組 copy
 * */
void mystrcopy(char *str1,char* str2){
	int i =0;
	while(str1[i]!='0'){
		str2[i] = str1[i];
		i++;
	}
	str2[i] = '\0';
}
/**
 * 使用字符串copy
 * */
void mystrcopy2(char *str1,char *str2){
	while(*str1!='\0'){
		*str2 = *str1;
		str1++;
		str2++;
	}
	*str2 = '\n';
}

int main(int argc, char const *argv[])
{
	char *str1 = (char*)"my baby is luoluoyang";
	cout << "str1:"<<str1<<endl;
	char *str2;
	// malloc(sizeof(str2))
	mystrcopy2(str1,str2);
	cout << "str2:"<<str2<<endl;
	// free(str2);
	return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM