In: Computer Science
how to code the text with excess whitespace removed in C++. Whitespace includes spaces and tabs. Excess whitespace is:
• All whitespace at the beginning of the text.
• All whitespace at the end of the text.
• Any point in the text where more than a single whitespace character is used.
For instance, if the input text is: Welcome to C++ !
The output would be: Welcome to C++!
Sample output:
The screenshots are attached below for reference.
Please follow them for proper indentation and output.
Program to copy:
#include <iostream>
#include<string>
using namespace std;
int main()
{
char str[100]={0};
cout<<"Enter text:";
cin.getline(str,100);//read input from user
int i=0;
int k=0;
int space=0;
while(str[i]!='\0'){//loop till end of input
while(k==0 && str[i]==' ')//removinf spaces if oresent in
beginning
i++;
if(str[i]==' ')//if space occurs check for previous character
{
if(space==0){
str[k]=str[i];
k++;
space=1;
}
}
else if(str[i]=='!'){//check punctuation caracters
if(str[k-1]==' '){
str[k-1]=str[i];
}
else{
str[k]=str[i];
k++;
}
space=0;
}
else{
str[k]=str[i];
k++;
space=0;
}
i+=1;
}
str[k]='\0';//end the string
i=0;
while(str[i]!='\0'){//print the result string
cout<<str[i];
i++;
}
return 0;
}