Replacing one character with two

Hello guys,
I an new to c++ and tried to do a program wherein the user enters his name and each letter in that name gets replaced by two other letters , for example a get replaced by ka , b gets replaced by zu and something like this till z.

for example the output must be like:
name: ab
new name : kazu


This is the code I created but a letter can only be replaced by one letter than two

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <algorithm>
#include <iostream>
#include <string>
#include<conio.h>
using namespace std;

int main()
  {
	  char name[50];
	  cout<<"\n Enter your first name";
	  cin>>name;

  string s=name ;
   replace( s.begin(), s.end(), 'a', 'k' );
  cout << s << endl;
  getch();
  }


So my question is how to do this kind of program using strings
boost has that function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <boost/algorithm/string/replace.hpp>

int main()
{
    std::string name;
    std::cout << "\n Enter your first name";
    std::cin >> name;

    boost::replace_all(name, "a", "ka");
    boost::replace_all(name, "b", "zu");
    std::cout << name << '\n';
}

online demo: http://coliru.stacked-crooked.com/a/a3bc64ad6a7ea676

to write something like that yourself, you could use the member functions of std::string:

1
2
3
4
5
6
7
8
9
10
    std::string from = "a";
    std::string to = "ka";
    for( std::size_t pos = name.find(from);
         pos != std::string::npos;
         pos = name.find(from, pos)
       )
    {
        name.replace(pos, from.size(), to);
        pos += to.size();
    }
Last edited on
um I haven't learned to write programs which include :: and things , by the way is there a more simpler and easier way to do it in visual c++?
I very much doubt it's going to get any more simple than what Cubbi just wrote. It's only ten lines long!

As for ::, this references the namespace. Everything in standard C++ lives in the namespace 'std' and so you can either call things from the std namespace like this:
 
std::cout << "Word.";


Or like this:
1
2
3
using namespace std;

cout << "Word.";


Or
1
2
3
using std::cout;

cout << "Word.";


The using namespace ... is not recommended, because it exposes more than necessary.
well thanks
Topic archived. No new replies allowed.