Beginners Programs :

C Program To Remove Blank Spaces From String | C Programs

C program to remove all extra blank spaces from a given string – In this article, we will brief in on the several means to remove all extra blank spaces 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 means used 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.

As given in the image above, you need to enter a string first up.

The string entered here is as follows: ” hello welcome to cbeginners “

As you can see, there are quite a few blank spaces in the string entered above.

Hence, the string becomes like this after removing all the blank spaces:

“hellowelcometocbeginners”

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

Using Standard Method

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

2) To remove the spaces from the string

k=0. The for loop iterates through the string until the end of the string becomes to null.

a) s[i]=s[i+k].

b) If the element at s[i] is equal to white space or tab then increase the k value and decrease the i value.

Shift the elements right to white space or tab, to one position left as s[i]=s[i+k].

After all iterations of for loop, we will get the string without blank spaces.

3) After removing the blank spaces to print the string.

Output:

Using Function

  1. The main() calls the deleteblankspaces(char *s) function to delete the blank spaces from the string.

2) The function deleteblankspaces(char *s) shifts the elements right to white space or tab, to one position left using for loop with structure for(i=0;s[i];i++).

Shifts the element right to white space or tab, to one position left as s[i]=s[i+k] using for loop with structure for(i=0;s[i];i++) by increasing k value,decrease the i value.

After all iterations of for loop, we will get the string without having blank spaces.

3) Print the string.

Output:

Using Recursion

  1. The function deleteblankspaces(char *s) is the recursive function which calls itself recursively to delete the blank spaces from the string.

2) If the element at s[i] not null then

a) Initialize s[i]=s[i+k].

b) If the element at s[i] equal to white space or a tab then increase the k value and decrease the i value.

c) Increase the i value to go to the next element of the string and call the function itself.

The function calls recursively until the element of the string becomes to null.

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

Output: