Answer the question
In order to leave comments, you need to log in
How to replace a single backslash?
How to replace a single backslash (\) with \\ or / in a string (std::string)
Answer the question
In order to leave comments, you need to log in
Not highly optimized, but valid code.
CONST_STR = string_view or const string& depending on the version of C.
The output is the number of replacements.
size_t str::replace(
std::string& aString,
const char aWhat,
const char aByWhat)
{
size_t r = 0;
FOR_S(i, 0, aString.length())
if (aString[i] == aWhat) {
aString[i] = aByWhat;
++r;
}
return r;
}
size_t str::replace(
std::string &aString,
char aWhat,
CONST_STR aByWhat)
{
if (aByWhat.length()==1)
{ // Simple replace
return str::replace(aString, aWhat, aByWhat[0]);
}
// More complex replace
static const size_t szWhat = 1;
const size_t szByWhat = aByWhat.length();
size_t p = 0, r = 0;
while ((p = aString.find(aWhat, p)) != std::string::npos)
{
aString.replace(p, szWhat, aByWhat);
p += szByWhat;
++r;
}
return r;
}
changes (\) to (/)
for(int i = 0; i < strlen(str); ++i){
if(str[i] == '\\'){
str[i] = '/';
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question