C program to trim trailing white space from a string

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

Example

Input

Input string: "Lots of trailing white spaces.      "

Output

String after removing trailing white spaces: 
"Lots of trailing white spaces."

Required knowledge

Basic C programming, Loop, String, Function

Must know – Program to search last occurrence of a character in string

Logic to remove trailing white spaces

Logic to remove trailing white space characters is lot more easier and faster than removing leading white space characters. As in this case we need not to perform any character shifting operation.

Below is the step by step descriptive logic to remove trailing white space character.

  1. Input string from user, store it in some variable say str.
  2. Initialize a variable to store last index of a non-white space character, say index = -1.
  3. Run a loop from start of the str till end.
  4. Inside the loop if current character is a non-white space character, then update the index with current character index.
  5. Finally, you will be left with last index of non-white space character. Assign NULL character at str[index + 1] = ‘\0’.

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

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


int main()
{
    char str[MAX_SIZE];

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

    printf("\nString before trimming trailing white space: \n'%s'", str);

    trimTrailing(str);

    printf("\n\nString after trimming trailing white spaces: \n'%s'", str);

    return 0;
}

/**
 * Remove trailing white space characters from string
 */
void trimTrailing(char * str)
{
    int index, i;

    /* Set default index */
    index = -1;

    /* Find last index of non-white space character */
    i = 0;
    while(str[i] != '\0')
    {
        if(str[i] != ' ' && str[i] != '\t' && str[i] != '\n')
        {
            index= i;
        }

        i++;
    }

    /* Mark next character to last non-white space character as NULL */
    str[index + 1] = '\0';
}

Output

Enter any string: Lots of trailing white space.           

String before trimming trailing white space: 
'Lots of trailing white space.           '

String after trimming trailing white space: 
'Lots of trailing white space.'

Happy coding 😉