2015-01-05 37 views
-1

我需要从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; 
} 
+2

指望它们,并使用'memmove'。 –

+0

@iharob:但我不应该使用'string.h'的函数 –

+2

[你不应该在C中抛出malloc的结果](http://stackoverflow.com/questions/605845/do-i-cast-the-结果-的-的malloc)。 –

回答

2

问题是在spaces -= 1线。你只剩下1个空格。

+1

当我删除了这个,我只有'World'字 –

1

您可以使用指针算术向前移动tab指针,然后计算字符串中剩余的字符,然后为新字符串分配空间并将每个字符复制到新分配的空间。

这是如何做到这一点不strings.h

char* ex6(char *tab) 
{ 
    int i; 
    char *w; 
    while ((*tab == ' ') && (*tab != '\0')) 
     tab++; 
    w = malloc(mystrlen(tab) + 1); 
    i = 0; 
    while (*tab != '\0') 
     w[i++] = *tab++; 
    w[i] = '\0'; 
    return w; 
} 
+0

'memmove'和'strdup'都来自'string.h',它不可用于OP。 –

+0

@FrerichRaabe我知道,但他在代码中使用了'strlen',并没有提及'string.h'是被禁止的。 –

3

修改字符串就地允许剥离前导空格在一个相当紧凑的方式,因为你不需要计算出结果字符串的长度:

/* 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; 
} 
相关问题