-2

I have one string A B C. I need to replace space with underscore(_) in C++. Is there any function like we have in perl or java?

Input:

   char* string =  "A B C" 

Output

    A_B_C
Manish
  • 3,341
  • 15
  • 52
  • 87
  • 1
    Consider `std::string` for your purposes... – bash.d Mar 07 '13 at 08:33
  • [Possible duplicate](http://stackoverflow.com/q/5878775/1084416) – Peter Wood Mar 07 '13 at 08:33
  • I have chararacter string (char*), so don't want to use std::string functions. – Manish Mar 07 '13 at 08:40
  • 2
    @user15662 Why didn't you say so immediately? – Mark Garcia Mar 07 '13 at 08:41
  • you can always use std::string(char *) constructor and output string.c_str() output. Depends what kind of operations do you need. If size of string cannot change as in this case, just loop with strpos and replace. – Pihhan Mar 07 '13 at 09:51
  • 1
    NOTE: There is something inherently wrong with the question that is not addressed in the *duplicate* answers. The code in the question is obtaining a non-const pointer to a literal, which is a deprecated feature of the language. While the pointer is non-const, the literal is const, and trying to change it's contents (for the substitution) is undefined behavior. As others have mentioned, you need to start by creating a copy (`std::string` would be the natural choice, operate on that and then get a `char*` back if you need) – David Rodríguez - dribeas Mar 07 '13 at 13:17

4 Answers4

7

There is std::replace

#include <algorithm>
...
std::replace (s.begin(), s.end(), ' ', '_');
tozka
  • 3,211
  • 19
  • 23
4

Yes, there's std::replace() defined in <algorithm>:

#include <algorithm>
#include <string>

int main() {
  std::string input("A B C");
  std::replace(input.begin(), input.end(), ' ', '_');
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
3

There is std::replace function

std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
nogard
  • 9,432
  • 6
  • 33
  • 53
2

There is no equivalent replace member function.

You must first search for the space and then use std::string::replace

char *string = "A B C";
std::string s(string);
size_t pos = s.find(' ');
if (pos != std::string::npos)
    s.replace(pos, 1, "_");

With just a char*, put it first in a std::string and then apply one of the answers here.

If you want to avoid std::string and std::string methods altogether, use std::replace as the other answers already suggested

std::replace(string, string + strlen(string), ' ', '_');

or if you already know the string length

std::replace(string, string + len, ' ', '_');

But keep in mind, that you cannot modify a constant string literal.

If you want to do it manually, style

static inline void manual_c_string_replace(char *s, char from, char to)
{
    for (; *s != 0; ++s)
        if (*s == from)
            *s = to;
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198