Reputation: 31
People who learned how to type before word processors often add two spaces after a period ending a sentence. Write a function singleSpaces that accepts a string and returns that string with all occurrences of two spaces after a "." into changed single spaces.)
This is what I have; what am I doing wrong?
#include <cmath>
#include <iostream>
using namespace std;
string forceSingleSpaces1 (string s) {
string r = "";
int i = 0;
while (i < static_cast <int> (s.length())) {
if (s.at(i) != ' ') {
r = r + s.at(i);
i++;
} else {
r += ' ';
while (i < static_cast <int> (s.length()) && s.at(i) == ' ')
i++;
}
}
return r;
}
Upvotes: 1
Views: 778
Reputation: 19229
You might (re)use a more general function that replaces occurrences of a given string within a string with another string, as described here.
#include <string>
#include <iostream>
void replace_all(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
int main() {
std::string text = "I'm old. And I use two spaces. After periods.";
std::string newstyle_text(text);
replace_all(newstyle_text, ". ", ". ");
std::cout << newstyle_text << "\n";
return 0;
}
If you are not afraid of being on the cutting edge, you might consider using TR1 regular expressions. Something like this should work:
#include <string>
#include <regex>
#include <iostream>
int main() {
std::string text = "I'm old. And I use two spaces. After periods.";
std::regex regex = ". ";
std::string replacement = ". ";
std::string newstyle_text = std::regex_replace(text, regex, repacement);
std::cout << newstyle_text << "\n";
return 0;
}
Upvotes: 2
Reputation: 50016
In your assignment there is talk about double spaces after dot, and not all double spaces in text. So you should modify your code so that it
you can think of this code as two states machine:
state 1 - is when you are looping on any non '.' character, in this state your code adds to result all what it finds
state 2 - is when '.' is found, and in this state you use different code, you add '.' to results and ater that exactly single space (if any one was found)
this way you have your problem divided into two sub problems
[edit] - replaced source code with modification hints
Upvotes: 2
Reputation: 37894
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
//1. loop through the string looking for ". "
//2. when ". " is found, delete one of the spaces
//3. Repeat process until ". " is not found.
string forceSingleSpaces1 (string str) {
size_t found(str.find(". "));
while (found !=string::npos){
str.erase(found+1,1);
found = str.find(". ");
}
return str;
}
int main(){
cout << forceSingleSpaces1("sentence1. sentence2. end. ") << endl;
return EXIT_SUCCESS;
}
Upvotes: 0