views:

532

answers:

2

What C function, if any, removes all preceding spaces and tabs from a string?

Thanks.

+8  A: 

In C a string is identified by a pointer, such as char *str, or possibly an array. Either way, we can declare our own pointer that will point to the start of the string:

char *c = str;

Then we can make our pointer move past any space-like characters:

while (isspace(*c))
    ++c;

That will move the pointer forwards until it is not pointing to a space, i.e. after any leading spaces or tabs. This leaves the original string unmodified - we've just changed the location our pointer c is pointing at.

You will need this include to get isspace:

#include <ctype.h>

Or if you are happy to define your own idea of what is a whitespace character, you can just write an expression:

while ((*c == ' ') || (*c == '\t'))
    ++c;
Daniel Earwicker
Technically, this will move the pointer "c" to the first non-space character, assuming it started out at the start of the string. It doesn't change the string at all. I point this out because if you have another pointer to the start of the string, it will still point to the original start of the string which may have spaces in it.To be clear, this technique is greatly preferred, since you're not moving bits around in the string, but you have to be aware you're moving the pointer, not eliminating the spaces. You have to understand pointers well to understand the difference.
dj_segfault
Good point, I've hopefully improved the explanation to cover that.
Daniel Earwicker
A: 
void trim(const char* src, char* buff, const unsigned int sizeBuff)
{
    if(sizeBuff < 1)
    return;

    const char* current = src;
    unsigned int i = 0;
    while(current != '\0' && i < sizeBuff-1)
    {
     if(*current != ' ' && *current != '\t')
      buff[i++] = *current; 
     ++current;
    }
    buff[i] = '\0';
}

You just need to give buff enough space.

young
Oops, I thought you wanted to remove "all" spaces and tabs in a given string. I missed "preceding". hope it helps someone else. :)
young
You can compress in situ since the output is smaller than the input.
Jonathan Leffler