c - 如何删除动态字符数组中的前导空格?

标签 c arrays string malloc

我需要从 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/

相关文章:

java - 将原始 int 数组类 (int[].class) 传递给需要 Class<T[]> 的泛型方法无法编译

Python 逆向模板,从字符串中获取变量

c - Linux 内核从 kzalloc 取消引用 memset 中的 NULL 指针

ios - 为对象双属性排序数组

javascript - 如何在 react 中的 map 函数中将对象作为 Prop 传递

java - 如何在给定数字中缺少数字的文件中用数字拆分?

c - 使用 scanf 在 C 中向后打印字符串

c - 什么会导致 exec 失败?接下来发生什么?

c - 我的浮点代码或 gcc 中有错误吗?

c - 设备驱动程序缺少 config.h