How to left-trim a C string

H

In several cases we would like to remove any leading white-spaces in a C-string. The following code snippet does this in the simplest possible way.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void str_ltrim_whsp(char* arg)
{
    if (arg == NULL)
        return;

    if (strlen(arg) == 0)
        return;

    int nhead = 0;

    while (arg[nhead++] == ' ');

    nhead--;
    memmove(arg, &arg[nhead], strlen(arg) - (nhead));
    arg[strlen(arg) - (nhead)] = '\0';
}
/// Example for Testing the function

int main()
{
    char test0[] = "Hello There!!!";
    char test1[] = "  Hello There!!!";
    char test2[] = "   Hello There!!!";

    str_ltrim_whsp(test0);
    str_ltrim_whsp(test1);
    str_ltrim_whsp(test2);

    return 0;
}

Add comment

Categories

Tags