C program to trim leading white space characters in 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. Trimming leading blank space characters from a string in C.

Example:
Input string:       Lots of leading space.
Output: Lots of leading space.

Required knowledge

Basic C programming, Loop, String, Function

Logic to remove leading white space

White space characters include Blank space(' '), Tab('\t'), New line('\n'). To remove leading white space characters from a string we need to perform two basic tasks:
  1. Run a loop from starting of string till a white space is found.
  2. Shift all characters to its left from the last leading white space character found above.


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 size of the string


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



int main()
{
    char string[MAX_SIZE];

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

    printf("String before trimming leading whitespace: %s\n", string);

    trimLeading(string);

    printf("String after trimming leading whitespace: %s\n", string);

    return 0;
}




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

    lastSpaceIndex = 0;

    /* Finds the last index of whitespace character */
    while(string[lastSpaceIndex] == ' ' || string[lastSpaceIndex] == '\t' || string[lastSpaceIndex] == '\n')
    {
        lastSpaceIndex++;
    }


    /* Shits all trailing characters to its left */
    i = 0;
    while(string[i + lastSpaceIndex] != '\0')
    {
        string[i] = string[i + lastSpaceIndex];
        i++;
    }
    string[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 ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment