C,C++/개념 실습 프로그래밍
[C언어] strcat함수 직접 구현
luckybee
2022. 10. 26. 19:45
728x90
반응형
두 문자열을 이어 붙이는 strcat함수를 직접 구현해보는 코드를 작성해보자
코드는 아래와 같다.
#include<stdio.h>
char* ApeendString(char a_dest[], const char a_src[])
{
int index = 0;
while (a_dest[index]){ //저장할 문자열을 널값까지 넘긴다.
index++;
}
int i;
for (i = 0; i < a_src[i]; i++){
a_dest[index + i] = a_src[i]; //널값부터 새로 이어붙힐 문자열을 대입한다.
}
a_dest[index + i] = 0; //끝에 널값을 넣는다.
return a_dest; //완성된 문자열의 시작 주소를 반환한다.
}
int main()
{
char str[10] = "abc";
ApeendString(str, "def");
printf("%s", str); //반환된 문자열은 str에 대입된다.
return 0;
}
결과는 아래와 같다
더보기
abcdef
만약 AppendString 함수를 포인터로 구성하면 어떻게 코드가 나올까?
답은 아래와 같다.
#include<stdio.h>
char* ApeendString(char *ap_dest, const char * ap_src)
{
char* ap_dest_pos= ap_dest; //시작 주소 백업
while (*ap_dest){
ap_dest++; //널값까지 반복
}
while (*ap_dest++ = *ap_src++); //ap_srcdl 널일 때까지 값을 계속 대입
return ap_dest_pos; //시작주소 반환
}
int main()
{
char str[10] = "abc";
ApeendString(str, "def");
printf("%s", str);
return 0;
}
728x90
반응형