문자열 여러개 합쳐야 하는데 free처리가 너무 불편해서..
원하는 만큼 문자열을 합칠 수 있는 함수입니당
char *str_joins(char **strs, int n)
strs
: 합쳐질 문자열 배열n
: 합쳐질 문자열 개수합쳐진 문자열
NULL
int main(void)
{
char *test;
char *comma;
char **arg;
test = "hi";
comma = ",";
arg = (char *[3]){ // [n] 안에 합칠 문자열 개수를 넣기. count 함수 등 활용가능
test,
comma,
test
};
// 방법 1
char *output = str_joins(arg, 3);
printf("%s\\n", output); // 출력 확인
return (0);
}
// 방법 2
/* 변수에 할당하지 않아도 사용가능하다. */
char *output = str_joins((char *[3]){"hello", " world" " !"}, 3);
printf("%s\\n", output); // 출력 확인
// 방법 1
hi,hi
// 방법 2
hello world !
char* str_joins(char **strs, int n)
{
char *temp;
char *output;
int idx;
idx = 0;
output = strdup(strs[idx]);
while (output && ++idx < n)
{
temp = strdup(output);
// strdup 실패시 null 리턴 추가해도됨
free(output);
output = strjoin(temp, strs[idx]);
free(temp);
}
return (output);
}