E
E
Emil Timerbaev2021-08-01 19:55:44
C++ / C#
Emil Timerbaev, 2021-08-01 19:55:44

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

3 answer(s)
D
Developer, 2021-08-01
@samodum

replace

M
Mercury13, 2021-08-01
@Mercury13

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;
}

L
LoliDeveloper, 2021-08-01
@LoliDeveloper

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 question

Ask a Question

731 491 924 answers to any question