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.

Thanks in advance!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
string formatEncrypt(string message)
{
    int msgLength=message.length();

    for(int i=0;i<msgLength;i++)
    {
        if(message[i] == 'j')
        {
            message[i]='i';
        }

    }

    if(msgLength % 2 != 0)
    {
        message=message+"x";
    }
    msgLength=message.length();

    for(int j=0;j<msgLength;j=j+2)
    {
        if(message[j+1]== message[j])
        {
            message=message+" ";
            msgLength=message.length();

            for(int k=msgLength-1;k>j;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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
 

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;
}
thank you vlad!
You are a life saver!
Topic archived. No new replies allowed.