0

how do I delete just the first spaces or tabs in string?

char* DelFistSpace(char* s){
    int i,k=1;
    char * out=s;
    for(i=0;s[i]!='\n';i++)
        if((s[i]!=' ' && s[i]!='    ')  || k==0){
            out[i]=s[i];
            k=0;
        }
        out[i]='\0';
        puts(out);
        return out;
}

For example: DelFistSpace("(space)(space)(space)a a");

expected: "a a"

igoris
  • 1,476
  • 10
  • 20
Elias Pinheiro
  • 237
  • 3
  • 11
  • The dupe-linked question has such good-quality answers, it's better to try and adapt those than get another one for this special case here, in my opinion. – unwind Nov 06 '13 at 15:44
  • @unwind Just went through answers in http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way. Sadly, at least 2 have potential UB dealing with trimming at the end. Maybe use `int` when `size_t` or `ssize_t` would be better. Even the accepted one fails using memcpy when memmove should be used for potential overlapping source and destination. – chux - Reinstate Monica Nov 06 '13 at 16:48

1 Answers1

2

Assuming client code will keep track of the original pointer if it needs to delete dynamically allocated memory, you could simply use

char* SkipLeadingSpaces(char* s){
    while (isspace(*s)) {
        s++;
    }
    return s;
}

If you want to keep using the original pointer in client code, just without the leading spaces, you could try something like

void RemoveLeadingSpaces(char* s){
    int trim = 0;
    char* trimmed = s;
    while (isspace(*s)) {
        s++;
    }
    for (; *s; s++) {
        *trimmed++ = *s;
    }
    *trimmed = '\0';
}
simonc
  • 41,632
  • 12
  • 85
  • 103