-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
6
  • 1
    Consider std::string for your purposes... Commented Mar 7, 2013 at 8:33
  • Possible duplicate Commented Mar 7, 2013 at 8:33
  • I have chararacter string (char*), so don't want to use std::string functions. Commented Mar 7, 2013 at 8:40
  • 2
    @user15662 Why didn't you say so immediately? Commented Mar 7, 2013 at 8:41
  • 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) Commented Mar 7, 2013 at 13:17

4 Answers 4

7

There is std::replace

#include <algorithm>
...
std::replace (s.begin(), s.end(), ' ', '_');
Sign up to request clarification or add additional context in comments.

Comments

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(), ' ', '_');
}

Comments

3

There is std::replace function

std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'

1 Comment

Amazingly similar to this answer stackoverflow.com/a/2896627/597607
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;
}

2 Comments

std::string function are very expensive. I need to do this 1 million times. It will slow down the speed.
@user15662 Then use std::replace, as the other answers suggest.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.