So, just need someone to help me figure out what's wrong with my code, and how I can fix it. I've looked up other sources, but I'd rather someone who knows what they're looking at to maybe explain what I've done wrong... I had it 'working' at some point, but it stopped after the first punctuation mark. I understand that creating an array is probably not the best idea, and that I can't add to the iterator, but I'm not sure how else to do it. Any suggestions?
I think this will help you clean up your code, pay attention to how the position returned from find can be used to find all occurrences of your search string.
Thank you for a response, and I did use that resource, but that's where the problems came in for stopping at the first sign of punctuation.
I ended up using replace, as find was giving me difficulties, and replacing is exactly what I want to do... getting all sorts of errors, but this seems right? The errors are all very long so maybe I'm constructing something incorrectly?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <algorithm>
usingnamespace std;
string doubleToSingleSpace (string userInput); //nonworking
int main()
{
string input = "this. is. a. test. string.";
cout << doubleToSingleSpace(input);
return 0;
}
I think this will help you clean up your code, pay attention to how the position returned from find can be used to find all occurrences of your search string.
Find ended up being very helpful, thank you clanmjc.
So I fixed it... for anyone who needs help with this, here's my new code. Note I did construct incorrectly(it MUST be userInput.replace. The way I got it to work is:
1 2 3 4 5 6 7 8 9 10
#include<string> //must include string, which I did,
// but this is a good thing to check for
usingnamespace std;
main int();
{
string s1("sample string");
s1.replace(beginningCharToReplace, numberOfCharsToReplace, whatToReplaceItWith)
}
My code for this program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
string doubleToSingleSpace (string userInput) //make sure function and inputs are both strings, if using outside string.
{ //to use replace function, make sure to pass by value, not by reference(string &userInput) which makes a copy, doesnt
// change the original.
size_t found; //index for the string called found
found = userInput.find(". "); // find the first period with two spaces
while(found != string::npos) // while found is not at the end of the string
{
userInput.replace(found+1, 2, " "); // move one position forward from found(ignore period),
//replace the next two positions, with " "
found = userInput.find(". "); //find next instance
}
return userInput; //changed string is returned