상세 컨텐츠

본문 제목

[c언어] strcpy 함수 구현

c언어

by ~지우~ 2021. 10. 28. 09:15

본문

728x90

오늘은 strcpy 함수를 직접 구현해보겠습니다.

 

strcpy함수는 문자열을 다른 문자열에 복사하는 함수로 <string.h>함수에 선언되어있습니다.

strcpy는 문자열을 복사한 곳의 문자열 포인터를 반환합니다.

 

포인터를 이용한 함수 구현

#include <stdio.h>

//strcpy 함수 구현
char* string_copy(char* s1, char* s2) {
	while (*s2 != '\0') {
		*s1 = *s2;
		s1++;
		s2++;
	}
	*s1 = '\0';

	return s1;
}

//string_copy 함수 호출
void main() {
	char sen1[30] = "hello";
	char sen2[30] = "world";
	string_copy(sen1, sen2);
	printf("%s\n", sen1);
}

 

배열을 이용한 함수 구현

#include <stdio.h>

//strcpy 함수 구현
char* string_copy(char s1[], char s2[]) {
	int i = 0;
	
	while (s2[i] != '\0') {
		s1[i] = s2[i];
		i++;
	}
	s1[i] = '\0';
	return s1;
}

//string_copy 함수 호출
void main() {
	char sen1[30] = "hello";
	char sen2[30] = "world";
	string_copy(sen1, sen2);
	printf("%s\n", sen1);
}
728x90

관련글 더보기

댓글 영역