C program to trim leading white spaces from a string

Write a C program to trim leading white space characters from a given string using loop. How to remove leading white space characters from a given string using loop in C programming. Logic to remove leading/starting blank spaces from a given string in C programming.

Example

Input

Input string:       Lots of leading space.

Output

String after removing leading white spaces: 
Lots of leading space.

Required knowledge

Basic C programming, Loop, String, Function

Must know – Program to remove elements from array

Logic to remove leading white space

White space characters include blank space ‘ ‘, tab ‘\t’, new line ‘n’.
Below is the step by step descriptive logic to remove leading white space characters from string.

  1. Input string from user, store it in some variable say str.
  2. Declare a variable to store last index of leading white space character, say index = -1. Initially I have assumed that there are no leading white space characters. Hence, index is initialized to -1.
  3. Run a loop from start till leading white space characters are found in str. Store the last index of leading white space character in index.
  4. Check if index == -1, then the given string contains no leading white space characters.
  5. If index != -1, then shift characters to left from the current index position.

Program to trim leading white space

/**
 * C program to trim leading white space characters from a string
 */
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
void trimLeading(char * str);


int main()
{
    char str[MAX_SIZE];

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    printf("\nString before trimming leading whitespace: \n%s", str);

    trimLeading(str);

    printf("\n\nString after trimming leading whitespace: \n%s", str);

    return 0;
}


/**
 * Remove leading whitespace characters from string
 */
void trimLeading(char * str)
{
    int index, i, j;

    index = 0;

    /* Find last index of whitespace character */
    while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n')
    {
        index++;
    }


    if(index != 0)
    {
        /* Shit all trailing characters to its left */
        i = 0;
        while(str[i + index] != '\0')
        {
            str[i] = str[i + index];
            i++;
        }
        str[i] = '\0'; // Make sure that string is NULL terminated
    }
}

Output

Enter any string:       Lots of leading space!

String before trimming leading whitespace:
       Lots of leading space!

String after trimming leading whitespace: 
Lots of leading space!

Happy coding 😉