Description:
Simple, remove the spaces from the string, then return the resultant string.
For C, you must return a new dynamically allocated string.
#include <stdlib.h>
char *no_space(const char *str_in)
{
char *ptr;
int i = 0, j = 0, len = 0;
while (str_in[i])
{
if (str_in[i] != ' ')
len++;
i++;
}
if (!(ptr = (char*)malloc(sizeof(char) * len + 1)))
return NULL;
i = 0;
while (str_in[i])
{
if (str_in[i] != ' ')
ptr[j++] = str_in[i];
i++;
}
ptr[len] = '\0';
return ptr;
}
another solution
char *no_space(char *s) {
char *res = strdup(s), *q = res;
for (; *s; s++)
if (*s != ' ')
*q++ = *s;
return *q = 0, res;
} -> strdup() function : 문자열 동적할당해주고 카피해주는데 이렇게 하면 직접 쓸 메모리공간보다 더 할당해주기 때문에 낭비될 수 있음.