Latest :

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

C program to trim leading whitespace characters from given string – In this article, we will report in on the manifold methods to trim leading whitespace 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 White Space Characters From String

As we can see in the image uploaded, we need to enter a string.

The string entered here is ”     Hello hello”

Hence, it is seen that there are leading whitespaces.

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

“Hello hello”

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

Using Standard Method

  1. Read the entered string and store into the character array variable ‘s’ using gets(s) function.

2) Print the string before trimming leading white spaces.

3) The first for loop iterates from starting of the string to till all leading white spaces present in the string. At the last iteration, the value of i indicates the index of the first non-white space character of the string.

4) Arrange the characters from zero index as s[j++]=s[i] using for loop for(j=0;s[i];i++).

5) After removing leading whitespaces, print the string.

Output:

Using Function

  1. The main() function calls the trimleading(char *s) function to remove the leading white spaces from the string.

2) The first for loop of the function iterates from i=0 to till the white spaces present in the string. Then the last value of i indicates the index of the starting non-whitespace character of the string.

3) Shift the characters of the string to left as s[j++]=s[i] using for loop for(j=0;s[i];i++).

4) Print the string after removing leading whitespace characters from the string.

Output:

Using Recursion

  1. The function count(char *s) calls itself recursively till the white spaces present in the string. It returns the i value.i is the number of leading white spaces present in the string.

2) The function trimleading(char *s) calls itself recursively till the elements of the string shift to left by i positions. Then initialize the last element of the string with the null.

3) The main() function prints the string after removing leading white spaces.

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 ...