1

I want to replace the string text=s_o_m_e=text with text=s-o-m-e=text

I have a starting and ending index:

std::string str("text=s_o_m_e=text");

std::string::size_type start = str.find("text="), end;

if (start != std::string::npos) {
    end = str.find("=", start);

    if (end != std::string::npos) {
        //...
    }
}

So, I'm looking for a function like this:

replaceAll(string, start, end, '_', '-');

UP:

std::replace(str.begin() + start, str.begin() + end, '_', '-');

Thanks, Blastfurnace

Community
  • 1
  • 1
Duglas
  • 251
  • 3
  • 9
  • 1
    Exact duplicate of [this question](http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string). – Eitan T Jun 04 '12 at 07:18

2 Answers2

10

There is a function in <algorithm> for that.

std::replace(str.begin(), str.end(), '_', '-');
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
  • More thx! So, my solution: `std::replace(str.begin() + start, str.end() + end, '_', '-');` – Duglas Jun 04 '12 at 07:17
  • 4
    @Duglas: You don't want to reference past the end of the string. Because you are using offsets, I think you want `std::replace(str.begin() + start, str.begin() + end, '_', '-');` – Blastfurnace Jun 04 '12 at 07:21
  • There is a huge limitation of using std::replace, the old_string and new_string must have the same length. i.e. std::replace(my_str.begin(), my_str.end(), "old string", "can't touch this"); will fail at template argument deduction i.e. "template argument deduction/substitution failed; note: deduced conflicting types for parameter ‘const _Tp’ (‘char [11]’ and ‘char [17]’)" – Alex Bitek Dec 03 '12 at 15:26
  • @BadDesign: It's not so much a limitation as a misuse of the algorithm. Your example wouldn't work even if the string literals were the same length. `std::string` is a container of `char` elements and those string literals can't be converted from `const char *` to `char`. – Blastfurnace Dec 03 '12 at 16:30
  • @Blastfurnace Right. Is there anything in the C++ Standard Library that does what I did in my example? (Something like you can do with boost::algorithm::replace_all(my_str, "test", "qwertyuiop")) – Alex Bitek Dec 03 '12 at 19:42
  • 1
    @BadDesign: Unfortunately, I don't think there's a simple Standard Library replacement for that Boost function. You'd probably have to do it the hard way using [`std::string::find`](http://en.cppreference.com/w/cpp/string/basic_string/find), [`std::string::erase`](http://en.cppreference.com/w/cpp/string/basic_string/erase), and [`std::string::insert`](http://en.cppreference.com/w/cpp/string/basic_string/insert). – Blastfurnace Dec 03 '12 at 19:52
5

Use std::replace. Here is more details.

besworland
  • 747
  • 2
  • 7
  • 17