몸과 마음이 건전한 SW 개발자

프로그래머스 [Lv. 0] 문자열 겹쳐쓰기 {언어 : C언어} 본문

개발 언어 입문/C언어

프로그래머스 [Lv. 0] 문자열 겹쳐쓰기 {언어 : C언어}

스위태니 2024. 2. 17. 22:48

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/181943

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

정답 코드 1

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h> // strlen과 strcpy를 사용하기 위해 추가

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* my_string, const char* overwrite_string, int s) {
    int len_my_string = strlen(my_string); // my_string의 길이 계산
    int len_overwrite_string = strlen(overwrite_string); // overwrite_string의 길이 계산
    
    // 동적 메모리 할당: my_string의 길이 + 1(null 종료 문자)
    char* answer = (char*)malloc(len_my_string + 1);
    
    // my_string을 answer에 복사
    strcpy(answer, my_string);
    
    // overwrite_string을 answer의 적절한 위치에 복사
    for (int i = 0; i < len_overwrite_string; ++i) {
        answer[s + i] = overwrite_string[i];
    }
    
    // answer 문자열에 null 종료 문자 추가
    answer[len_my_string] = '\0';
    
    return answer;
}

정답 코드 2 (memcpy)

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h> // strlen, strcpy, memcpy를 사용하기 위해 추가

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* my_string, const char* overwrite_string, int s) {
    int len_my_string = strlen(my_string); // my_string의 길이 계산
    int len_overwrite_string = strlen(overwrite_string); // overwrite_string의 길이 계산
    
    // 동적 메모리 할당: my_string의 길이 + 1(null 종료 문자)
    char* answer = (char*)malloc(len_my_string + 1);
    
    // my_string을 answer에 복사
    strcpy(answer, my_string);
    
    // overwrite_string을 answer의 s 인덱스부터 시작하는 위치에 memcpy를 사용해 복사
    memcpy(answer + s, overwrite_string, len_overwrite_string);
    
    // answer 문자열에 null 종료 문자 추가
    answer[len_my_string] = '\0';
    
    return answer;
}

정답 코드 3

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* my_string, const char* overwrite_string, int s) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    // 이 코드는 my_string의 길이에 1을 더한 만큼의 문자 공간을 동적으로 할당하여, 그 메모리 주소를 answer 포인터에 저장합니다.
    char* answer = (char*)malloc(strlen(my_string)+1);
    for(int i=0; i < strlen(my_string); i++) answer[i] = my_string[i];
    for(int i=s; i < s + strlen(overwrite_string); i++) answer[i] = overwrite_string[i-s];
    answer[strlen(my_string)]='\0';
    return answer;
}