0

I am using this code to replace a letter in a string it works fine but it removes the first letter that i need to keep. I only need a * in the centre of the string but this problem has stumped me.

textWords[i].replace(pos, 2 , 1 , '*');

All the words i am replace the middle character in are three characters long and it always get rid of the first character as well. The replace function is the one used for vectors i did not write it and pos is defined by the code below.

 size_t pos = textWords[i].find(bannedWords[j]);

Any help is appreciated.

4
  • So what do you want exactly? If "bar" is a banned word. How would it end up if you used your replace function? "b*r"? Commented Mar 15, 2012 at 17:05
  • @fontanini Yes that is how it should end up b*r but it currently show up like *r missing the first letter. Commented Mar 15, 2012 at 17:08
  • Check my answer, i think that will work then. Commented Mar 15, 2012 at 17:09
  • 4
    if (pos != npos) textWords[i][pos + 1] = '*'; ?? Commented Mar 15, 2012 at 17:11

2 Answers 2

3

I believe you are trying to replace the second character from each banned word with an asterisk. You have to call std::string::replace using these arguments:

textWords[i].replace(pos + 1, 1, 1 , '*');

This way you are removing the second character(pos + 1), and replacing it with one asterisk.

EDIT: As @Dan pointed out, you can also just assign the character:

textWords[i][pos + 1] = '*';
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked perfectly such a simple solution. Don't know why i didn't think of it.
1

The second argument in your replace parameters specifies how many characters to remove. Change it to 1 and it should do what you want:

textWords[i].replace(pos, 1 , 1 , '*');

1 Comment

I have tried that and that gets rid of the first letter and leaves the last two. I might not have been clear it is the centre letter that i want to replace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.