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
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
There is std::replace
#include <algorithm>
...
std::replace (s.begin(), s.end(), ' ', '_');
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(), ' ', '_');
}
There is std::replace
function
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
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, c style
static inline void manual_c_string_replace(char *s, char from, char to)
{
for (; *s != 0; ++s)
if (*s == from)
*s = to;
}