0

well I would like to know how to change number by letter, I would like to replace the number 1 with :x: Here's my code:

string stng;

printf("Enter with number:");
cin >> stng;

replace(stng.begin(), stng.end(), '1', 'x');

cout << stng << endl;

as you can see I'm using this to replace: replace(stng.begin(), stng.end(), '1', 'x'); but as soon as I can only change 1 for x, I want to replace for :x:

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
Ph4nton
  • 48
  • 1
  • 8
  • http://stackoverflow.com/questions/4643512/… http://stackoverflow.com/questions/3418231/… I seems for C++ it is not so trivial task :(. – Dzenly Dec 11 '15 at 04:16
  • Possible duplicate of [How to replace all occurrences of a character in string?](http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string) – prazuber Dec 12 '15 at 14:37

4 Answers4

0

Maybe you can try something like this

string stng;

printf("Enter with number:");
cin >> stng;

replace(stng.begin(), stng.end(), '1', ":x:");

cout << stng << endl;
bl4ckb0ne
  • 1,097
  • 2
  • 15
  • 30
0

Here's what I use. It will take a std::string and replace all occurrences of the from input string to the to input string.

std::string replaceAll(const std::string & s, const std::string & from, const std::string & to)
{
    string res(s);
    string::size_type n1 = from.size();
    string::size_type n2 = to.size();
    string::size_type i = 0;
    string::size_type j = 0;
    while ((i = res.find(from, j)) != string::npos)
    {
        res.replace(i, n1, to);
        j = i + n2;
    }
    return res;
}
Anon Mail
  • 4,660
  • 1
  • 18
  • 21
0

You can do that better with the replace member function of std::string.

auto pos = stng.find("1"); // search for 1 in the string
if (pos!=stng.npos)  // check if 1 is found
{
   stng.replace(pos, 1, ":x:");   // replace ":x:" starting from 'pos' to 'pos+1'
}

And your job is done !!!

Ankit Acharya
  • 2,833
  • 3
  • 18
  • 29
  • 1
    Hum that's nice, is working very well! I had never seen "auto" in C ++ will study more about it! thx :D – Ph4nton Dec 11 '15 at 20:25
0

You can split the string by delim '1' into tokens using this split function.

Then merge the string by ":x:" using the following function

std::string merge(const std::vector<std::string>& v, const std::string& glue)
{    
    std::string result;
    if(v.empty()) { return result; }
    result += v[0];
    for(size_t i = 1; i != v.size() ; i++)
    {
        result += glue;
        result += v[i];
    }
    return result;
}

std::string replace(const std::string& src, char delim, const std::string& glue)
{
    return merge(split(src, delim), glue); 
}

Live is here

Community
  • 1
  • 1
Chen OT
  • 3,486
  • 2
  • 24
  • 46