• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
August 31, 2022 |740 Views

C Program to Trim Trailing White Spaces from String

  Share  1 Like
Description
Discussion

In this video, we will see how to write a C Program to Trim Trailing White Spaces from String.

Method:
The idea is to count the trailing spaces in the given string and then from that count index copy the characters from that index to the rear of the string.
 
Examples :
Input: str = ”geeksforgeeks         ”
Output: geeksforgeeks

Algorithm:

Step 1: Initialize the lastIndex variable with 0 and variable i with 0.
Step 2: Iterate through the given string and find the last non-whitespace character.
Step 3: Run a While loop till the last character of the given string and if the current character is non-whitespace char do 
lastIndex = currentIndex to get the last non-whitespace character.
Step 4: Now, from the first character till the last non-whitespace character copy the string into a new string.
Step 5: Finally, put ‘\0’ at the last index of the new string to terminate the string.
Step 6: Print output.