I need to remove leading spaces from dynamic character array in C. My application almost works, but it leaves just one space at the beginning. How to get rid of all leading spaces from the given text? I should not use functions from string.h
. Heres my code:
#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;
}