You are using a version without Ads of this website. Please, consider donating:

### how do i replace the 2nd occurrence of a letter with x?

Hi guys, supposed i have a word hammer.

how am i suppose to search for the 2nd occurrence of the letter and then replace it with x?

example hammer will become hamxer

I thought about using replace for it, however i`m lost on how to find 2 occurrences of the same letter in the word.

 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````string formatEncrypt(string message) { int msgLength=message.length(); for(int i=0;ij;k--) { message[k]=message[k-1]; } message[j+1]='z'; }else { } } return message; }``````

at line 31 i tried to put a z into the alphabet that occurs twice.

this is what i have done so far

example: hello world
It will turn out as helzlo world
However i want to make the output appear as helzo world
Last edited on
Are you going to replace the second letter of adjacent letters or any second occurence of a letter?
i`m going to replace any second occurrence of a letter
I would use an std::map<char, int>.

As you go through the letters of the message, you check if the letter is in the map.
If it isn't, add it with a mapped integer of 0 and move on to the next letter.
If it is, check the mapped integer. If it's 0, you replace the occurrence with x and change the integer to 1. If the mapped integer is already 1, move on to the next letter.

There are better ways than this, probably. I'd like to see what others have in mind.
hi catfish, thanks for your help.

However, i have to change the corresponding x back to the same letter again after decryption so i guess maps are out of the picture or correct me if i`m wrong if it can be done with maps.
 ``1234567891011121314151617181920212223`` ``````#include #include std::string ReplaceEachSecond( const std::string &s, char src, char dst ) { std::string t( s ); for ( std::string::size_type even = 0, pos = t.find( src, 0 ); pos != std::string::npos; pos = t.find( src, ++pos ) ) { if ( ( even = ++even % 2 ) == 0 ) t[pos] = dst; } return ( t ); } int main() { std::cout << ReplaceEachSecond( "aaaaaaa", 'a', 'b' ) << std::endl; }``````