我需要从C中的动态字符数组中删除前导空格。我的应用程序几乎可以工作,但它在开始时只留下一个空格。如何摆脱给定文本中的所有前导空格?我不应该使用string.h
的功能。继承人我的代码:如何删除动态字符数组中的前导空格?
#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'的函数 –
[你不应该在C中抛出malloc的结果](http://stackoverflow.com/questions/605845/do-i-cast-the-结果-的-的malloc)。 –