-1

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;
}
Brian Brown
  • 3,873
  • 16
  • 48
  • 79

3 Answers3

3

Modifying the string in-place allows stripping leading spaces in a fairly compact manner since you don't need to calculate the length of the result string:

/* 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;
}
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
2

The problem is in spaces -= 1 line. You go back 1 space left.

i486
  • 6,491
  • 4
  • 24
  • 41
1

You can just move the tab pointer forward using pointer arithmetic, and then count the remaining characters in the string, then allocate space for the new string and copy each character to the new allocated space.

This is how to do it without 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;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97