Latest :

C Program To Trim Trailing White Space Characters From String | C Programs

C program to trim trailing white space characters from string – In this article, we will detail in on the several ways to trim trailing white space characters from a given string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The ways explained in this piece are as follows:

  • Using Standard Method
  • Using Function
  • Using Recursion

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

C Program To Trim Trailing White Space Characters From Given String

As we can see with this easy example, we need to enter a string.

The string entered here is “hello world     ”

Hence, it is seen that there are trailing whitespaces.

So, after removing the trailing whitespaces, the string would be like:

“hello world”

Thus, the ways to do the same in C programming are as follows:

Using Standard Method

  1. Read the string entered by the user using gets(s) function.

2) Print the string before trim trailing white spaces from the string.

3) Initialize i=length of the string-1.

4) The while loop goes through the string in reverse order until i<-1 becomes to false.

If the character at s[i] equals to white space or tab then decrease the i value. Otherwise, terminate the loop. Repeat this step until i<-1. Here we removing the trailing white spaces from the string in reverse order.

5) Every string ends with a null character so initialize the last element of the string with a null character.

6) Print the string after trim trailing white spaces from the string.

Output:

Using Function

  1. The main() calls the trimtrailing(char *s) function to remove the trailing whitespaces of the string.

2) a) i=length of the string-1.

b) The while loop iterates until i>-1 becomes to false.

b.1) If the character at s[i] is a white space or tab then decrease i value. Otherwise,

b.2) Terminate the loop.

c) After removing all trailing white spaces ,initialize the last element s[i+1]=”\0″.

Output:

Using Recursion

  1. The main() calls the recursive function trimtrailing(char *s) which calls itself recursively to remove the trailing whitespace characters.

2) a) Initialize i=length of the string-1.

b) If the character at the last index is equal to the white space or a tab then decrease index value i by 1. Call the function itself. The function calls recursively until it removes the all trailing whitespaces of the string.

c) After removing the trailing whitespaces then terminate the loop.

d) Every string ends with the null character so initialize s[i+1]=”\0″.

Output:
x

Check Also

C Program To Find Reverse Of An Array – C Programs

C program to find the reverse of an array – In this article, we will ...