I'm looking to find out how to find characters in one string and replace characters in another string with the same character in the same position as the ones that were found in the first string...
I hope that makes sense.
Printable View
I'm looking to find out how to find characters in one string and replace characters in another string with the same character in the same position as the ones that were found in the first string...
I hope that makes sense.
Not really, sorry! ;)
But, assuming you are using the C++ string class, you can find a character or substring of characters using find, find_first_of, find_last_of, etc. You can also replace characters or strings using replace. If you combine the use of these functions you could probably do what you want, especially considering the find returns an index to the location of the found character that you could use to replace a character at the same index in another string.
I'm having issues with the replace method. When I include it in the below code, it compiles fine, but when I reach that section of code when I run the program, it mysteriously aborts...
Anyone know why?
Code:for (int i = 0; i < dashWord.length(); i++)
{
x = word.find_first_of(guess,i);
word.replace(x,1,guess);
i = x;
cout << dashWord;
}
Code:
string name;
name = "blob";
bob[0] = 'f';
cout << name; //flob
You should check the return value of find_first_of in case it wasn't found. If it wasn't, I believe string::npos is returned (which is basically -1), and so you can't use it with replace.
Also, I think find is sufficient instead of find_first_of, but I don't know what you are doing. Finally, maybe it should be dashWord.find(guess, i); instead of word.find(...). That's just a guess based on your description above of what you are trying to do.