C program to trim both leading and trailing white spaces in a string

Write a C program to trim both leading and trailing white space characters in a string using loop. How to remove both leading and trailing white space characters in a string using loop in C programming. Program to delete all leading and trailing white space characters from a given string in C.

Example:
Input string: "     Lots of leading and trailing spaces.     "
Output string: "Lots of leading and trailing spaces."

Required knowledge

Basic C programming, Loop, String, Function

Before moving on to this program if you haven't done with previous program on trimming spaces, it is recommended to go though both of them how to trim leading spaces and trailing spaces.

Program to trim leading and trailing white spaces

/**
 * C program to trim both leading and trailing white space characters from a string
 */

#include <stdio.h>
#define MAX_SIZE 100 //Maximum size of the string


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



int main()
{
    char string[MAX_SIZE];

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

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

    trim(string);

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

    return 0;
}




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

    /*
     * Trims leading white spaces
     */
    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



    /*
     * Trims trailing white spaces
     */

    /* Finds the last non white space character */
    i = 0;
    while(string[i] != '\0')
    {
        if(string[i] != ' ' && string[i] != '\t' && string[i] != '\n')
        {
            lastIndex = i;
        }

        i++;
    }

    /* Mark the next character to last non white space character as NULL */
    string[lastIndex + 1] = '\0';
}


Output
Enter any string:      Lots of white spaces.     
String before trimming whitespace: "     Lots of white spaces.     "
String after trimming whitespace: "Lots of white spaces."

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