Write a C program to trim leading white space characters from given string.

In this code snippet, we will learn how to trim leading and trailing whitespaces using c program. For example if you enter string " Hello World! ", after trimming output string will be "Hello World!" Program will be removed leading and trailing whitespaces from the string.

Required knowledge

Basic C programming, C if-else, C for loop, Array, functions, Strings

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: I love c programming
String before trimming leading whitespace:
I love c programming
String after trimming leading whitespace:
I love c programming



Instagram