Algorithm of Remove Whitespaces from source code:
- Input a string
- Finding the character of the white space by using the while loop.
- Find the null character inside the loop, when encountered, we increment the index.
- Next, we input the remaining characters in the new string, “newstr”.
- Displaying the new string.
The logic of Remove Whitespaces
Step 1: find out all nulls
Step 2: ignore all the nulls in a string
Step 2: store the remaining contents in another string.
C++ Code for Remove Whitespaces from the program
Write a C++ Program to delete whitespaces from the given string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//C++ Program to delete whitespaces from the given string #include <iostream> using namespace std; int main() { string str; cout<<"Please Enter the string "; getline(cin,str); int len=str.length(); char newstr[len]; //Removing one or more blank spaces from string int t4tutorials=0,dotcom=0; while(str[t4tutorials]!='\0') { while(str[t4tutorials] == ' ') //using loop to remove consecutive blanks t4tutorials ++; newstr[dotcom]=str[t4tutorials]; //newstr[dotcom ++]=str[t4tutorials ++] //we can also use this instead t4tutorials ++; dotcom ++; } newstr[len-1]='\0'; //To terminate the newstr, we use -1, because j was a post increment. cout<<"\n String after removal of blank spaces is:"<<newstr; return 0; } |
Output
Please Enter the string I LOVE T4TUTORIALS DOT COM
String after removal of blank spaces is: ILOVET4TUTORIALSDOTCOM