0

I want to replace my text with boost like php.

char* find = "a abc text";
char* search[] = { "a", "b", "c", "d", "e" };
char* replace[] = { "f", "g", "h", "i", "j" };
boost::replace_all(find, search, replace);

But he can't convert "char* const" to "int".

ThatName
  • 23
  • 1
  • It appears you are trying to do something similar to: [this](http://stackoverflow.com/a/4289916/2690204) You may want to look at how replace_all works, you are not passing a string along for search and replace. – Hashman Jun 17 '16 at 22:23
  • "he can't convert" is not a good, scientific problem description. To make this a good question for SO, describe in detail the problem you face, including error messages and what you did to solve them. – Lightness Races in Orbit Jun 18 '16 at 01:07

2 Answers2

2

In C++ string literals (like "a abc text") are read only, attempting to modify a string literal will lead to undefined behavior. That's why the code you show should cause the compiler to give you a warning (that you have a non-const pointer to const data), and if the compiler doesn't warn you then you need to enable more warnings. A pointer to a string literal should always by char const* or the more common const char *.

If you want a modifiable string, use std::string (or if you want C-style string use arrays of char, like char find[] = "a abc text").

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You actually don't need to use boost for something as trivial as this.

char value[]        = "foobar";
const char *search  = "abcde";
const char *replace = "fghij";

size_t i, j, k = strlen(value);

for (i = 0; i < 5; i ++) {
    for (j = 0; j < k; j ++) {
        if (value[j] == search[i])
            value[j] = replace[i];
    }
}

Note that this code assumes that there are 5 characters in search and replace. Also note that if search and replace overlap, there will be unexpected behaviour. If that is important to you, you should switch the order of for-loops (i.e. first j < k, then i < 5).

cutsoy
  • 10,127
  • 4
  • 40
  • 57