Removing Spaces in a String
In this lesson you will learn how to find the total number of spaces in a string.
What do we mean by spaces?
Given a particular string, we can find and remove the spaces in it. Spaces are the whitespaces in the text, i.e., the empty gaps within textual data. The illustration below shows what we aim to do!
Implementing the Code
The code below shows how to do this with recursion. First let’s see the code, then we can go on to its explanation.
Try the code by changing the values of text
to see how it works with other strings!
Press + to interact
#include <string>#include <iostream>using namespace std;void removeSpaces(string &text, int index,int len){if (len==0){return;}if(index==len){return;}if(text[index]==' '){int i=index;while(i<len){text[i]=text[i+1];i++;}removeSpaces(text,index,len-1);}removeSpaces(text,index+1,len);}int main(){ string text=" HO ME";cout<<text<<endl;removeSpaces(text,0,text.length());cout<<text<<endl;}
Understanding the Code
This code can be broken down into two parts. The first is the recursive function and the second is the main where the function is called.
Driver Function
The recursive function is called within the driver function so lets first look at what it does from line 28 to 32.