C program to trim trailing white space characters in a string

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

Example:
Input string: "Lots of trailing white spaces.      "
Output string: "Lots of trailing white spaces."

Required knowledge

Basic C programming, Loop, String, Function

Logic to remove trailing white spaces

We have already seen how to remove leading white space characters in a given string. Logic to trim trailing white space is far simpler than removing leading white space. Here what we need to do is:
  1. Run a loop from 0 to end of the string. Mark a position after which there is no non white space character. Call this position as endIndex.
  2. Mark the next character to endIndex with the NULL terminator and we are done.


Program to trim trailing white space characters

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

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


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



int main()
{
    char string[MAX_SIZE];

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

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

    trimTrailing(string);

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

    return 0;
}




/**
 * Remove trailing whitespace characters from a string
 */
void trimTrailing(char * string)
{
    int lastIndex, i;

    /* 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 trailing white space.     
String before trimming trailing whitespace: "Lots of trailing white space.     "
String after trimming trailing whitespace: "Lots of trailing white 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