Example:
Input string: "Lots of trailing white spaces. "
Output string: "Lots of trailing white spaces."
Required knowledge
Basic C programming, Loop, String, FunctionLogic 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:- 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.
- 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."
String before trimming trailing whitespace: "Lots of trailing white space. "
String after trimming trailing whitespace: "Lots of trailing white space."
Happy coding ;)
You may also like
- String programming exercises index.
- C program to trim leading and trailing white space characters in a string.
- 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 check whether a string is palindrome or not.
- C program to search all occurrences of a character in a string.
- C program to search all occurrences of a word in a string.
- C program to find highest frequency character in a string.
- C program to count frequency of each character in a string.
- C program to remove all occurrences of a character from a string.
- C program to remove all repeated characters from a string.