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.
- Input string from user, store it in some variable say str.
- Initialize a variable to store last index of a non-white space character, say index = -1.
- Run a loop from start of the str till end.
- Inside the loop if current character is a non-white space character, then update the index with current character index.
- 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 😉
Recommended posts
- String programming exercises index.
- C program to trim leading and trailing white space characters in a string.
- C program to trim leading white space characters.
- C program to remove extra blank spaces from a string.
- C program to toggle case of each character of a string.
- C program to count total number of words in a string.
- C program to search all occurrences of a character in a string.