FOR FREE YEAR SOLVED

Remove extra spaces between the words

Back to Programming

Description

A string is a sequence of characters. A string can be a word, multiple words or a sentence. Generally, in a sentence, there is one single space between the words. Here, in this program, the input string is taken with more than one space between the words. The program is written such that the extra spaces between the words will be squeezed i.e. the multiple spaces will be replaced by one space.

 

For example: 

If the input string is:  He           is                        a        boy.

Then the output string will be: He is a boy.

 

For this, whenever the character will be fetched from the original string it will be checked whether it is a blank space or not. If the character is a blank space then it will be skipped until a character is fetched which is not a blank space. And after skipping all the in-between spaces a single blank space will be appended to the string followed by the other characters (except space). This process will be continued till the last character of the string.

Algorithm

INPUT: A string with multiple blank spaces between words
OUTPUT: A string after squeezing the extra spaces.
PROCESS:
Step 1: [Taking the input]
	Read s [the input string]
Step 2:	[squeezing the blank spaces] 
	Set str=”” [Defining a null string to store the result]
	For i=0 to length(s)-1 repeat
		[if the character is a space set flag to 1 and continue the loop]
		If s[i] =' ' then
			Set j<-1
			continue
		[End of ‘if’]
		[if the flag is true, insert a single space into the squeezed string]
		If j=1 then
			Set str[c]=' '
			Set c<-c+1
			Set j<-0
		[End of ‘if’]
		[Insert the other characters into the string]
		Set str[c]<-s[i]
		Set c<-c+1	
	[End of ‘for’ loop]
	[Printing the final string after squeezing]
	Print "The string after squeezing: "
	Print str
[End of ‘squeezing’]
Step 3: Stop.

Code

Time Complexity:

The time complexity of squeezing the space is O(n) where n is the number of characters of the input string.

 

Space Complexity:

The space complexity of squeezing the space is O(n) where n is the number of characters of the input string.

Contributed by