본문 바로가기
알고리즘/코딩 테스트 문제

[프로그래머스] 특정 문자 제거하기(C)

by 진진리 2023. 9. 21.
728x90
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* my_string, const char* letter) {
    // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
    char* answer = (char*)malloc(sizeof(char)*strlen(my_string));
    int index=0;
    
    for(int i=0;i<strlen(my_string);i++){
        char a1 = my_string[i];
        char a2 = *letter;
        if(a1!=a2) answer[index++] = a1;
    }
    
    answer[index] = '\0';
    
    
    return answer;
}

answer 마지막에 널값을 주니 풀림  

 

문자열일 때 원하는 길이보다 +1해서 메모리 할당 후 널값을 넣어주면 오류 발생 x