How to left-trim a C string

H


In various instances, there’s a need to eliminate leading white spaces from a C-string. The provided code snippet efficiently accomplishes this task using a straightforward approach. By employing this uncomplicated method, unnecessary white spaces at the beginning of the C-string are effectively stripped away.

This simplistic solution proves useful in scenarios where a basic yet effective solution is sought for trimming leading white spaces from strings in C programming. It provides a clear and concise way to address this common requirement in a codebase.

#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;
}
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags