C의 동적 문자 배열에서 선행 공백을 제거해야합니다. 응용 프로그램이 거의 작동하지만 처음에는 공백이 하나만 남습니다. 주어진 텍스트에서 모든 선행 공백을 제거하는 방법? 나는 string.h
에서 기능을 사용해서는 안됩니다. Heres 내 코드 :동적 문자 배열에서 선행 공백을 제거하는 방법은 무엇입니까?
#include <stdio.h>
#include <stdlib.h>
int mystrlen(char *tab)
{
int i = 0;
while(tab[i] != '\0')
{
i++;
}
return i;
}
char* ex6(char *tab)
{
int spaces = 0, i, j = 0, s = 0;
for(i=0; tab[i] != '\0'; i++)
{
if (tab[i] == ' ')
spaces ++;
else
break;
}
spaces -= 1;
char *w = (char*) malloc (sizeof(char) * (mystrlen(tab) - spaces + 1));
for(i=0; tab[i] != '\0'; i++)
{
if (tab[i] == ' ')
{
++ s;
}
if(s > spaces)
{
w[j] = tab[i];
j ++;
}
}
w[j] = 0;
return w;
}
int main()
{
char txt[] = " Hello World";
char *w = ex6(txt);
printf("%s\n", w);
free(w);
w = NULL;
return 0;
}
그들을 계산하고'memmove'를 사용하십시오. –
@iharob :하지만'string.h'의 함수를 사용해서는 안됩니다 –
[malloc의 결과를 C로 캐스팅하지 마십시오] (http://stackoverflow.com/questions/605845/do-i-cast-the- malloc 결과). –