Remove extra spaces

When I type a sentence for an example "How are you."
I would want it to output "How are you.". How do I get the program to remove the extra spaces.


#include <iostream>
#include <string>
#include <limits>
#include <cctype>

using namespace std;

void takeLine(string & sentence);

int main()
{
string sentence;

cout << "Enter a sentence. ";
getline(cin, sentence);
cout << endl;
takeLine(sentence);


cout << "\nPress Enter to continue...\n";
cin.ignore(numeric_limits<streamsize>::max(),'\n');
return 0;
}

void takeLine(string & sentence)
{
string::size_type i = 0, p, last_p;

sentence[i] = static_cast<char>(toupper(sentence[i]));
for (i++; i < sentence.length(); i++)
{
sentence[i] = static_cast<char>(tolower(sentence[i]));
}
last_p = 0;
p = sentence.find_first_of("' .'");
while (p != string::npos ){

cout << sentence.substr(last_p,p-last_p);
last_p = p+1;

p = sentence.find_first_of("' .'", last_p);

if (p == string::npos)
{
cout << ' ' << sentence.substr(last_p,p-last_p) << ".";
}
else
{
cout << " ";
}
}
}
I meant to write How - are you? but this website took off the spaces it self.
one way is to read word by word into a vector of words, and put the spaces back yourself.
otherwise you can search for 2 spaces and replace with 1 via find() and erase functions, but you would have to do that in a loop until it didnt find any more to do. this is probably the worst approach I am offering; its on par with using a text editor to replace space space with space over and over.
and a third way is to copy letter by letter into a new string, skipping extra spaces.

you may have additional rules like space punctuation. If you want those, you probably want method #3.

and finally you can probably do it all in 2 lines with some difficult to follow string magic functions, but I am not quite there yet in cooking those up. Someone will offer one of those shortly, I am sure :)
Last edited on
Topic archived. No new replies allowed.