# Program to remove whitespaces from string in C++

Written by

Juhi Kamdar

Logic:

In this method, we find out all nulls and ignore all the nulls in a string and store the remaining contents in another string.

Algorithm:

1. Take a string input.
2. We run a loop, character by character to find the null/white space.
3. In the loop, we check the presence of null character, when encountered, we increment the index.
4. Next, we input the remaining characters in the new string, newstr.
5. Output the new string.

Code:

//removing blank space
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Enter the string ";
getline(cin,str);
int len=str.length();
char newstr[len];
//Removing one or more blank spaces from string
int i=0,j=0;
while(str[i]!='\0')
{
while(str[i] == ' ')//using loop to remove consecutive blanks
i++;
newstr[j]=str[i]; //newstr[j++]=str[i++] we can also use this instead
i++;
j++;
}
newstr[len-1]='\0';//terminating newstr, we use -1, as j was a post increment.
cout&lt;&lt;"\n String after removal of blank spaces is:"&lt;&lt;newstr;
return 0;

}

Output:

Enter the string: This Is A String Which Does Not Have Space!
String after removal of blank spaces is:ThisIsAStringWhichDoesNotHaveSpace!