Program to remove whitespaces from string in C++
Written by
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:
- Take a string input.
- We run a loop, character by character to find the null/white space.
- In the loop, we check the presence of null character, when encountered, we increment the index.
- Next, we input the remaining characters in the new string, newstr.
- 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<<"\n String after removal of blank spaces is:"<<newstr;
return 0;
}
Output:
Enter the string: This Is A String Which Does Not Have Space!
String after removal of blank spaces is:ThisIsAStringWhichDoesNotHaveSpace!