我需要从 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;
}
最佳答案
就地修改字符串可以以相当紧凑的方式去除前导空格,因为您不需要计算结果字符串的长度:
/* No includes needed for ltrim. */
void ltrim( char *s )
{
const char *t = s;
while ( *t && *t == ' ' )
++t;
while ( ( *s++ = *t++ ) )
;
}
#include <stdio.h>
int main()
{
char txt[] = " Hello World";
ltrim(txt);
printf("%s\n", txt);
return 0;
}
关于c - 如何删除动态字符数组中的前导空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782931/