jeudi 22 mars 2018

C++ Escape occurences of \ in a string

Is there a simple way to escape all occurences of \ in a string? I start with the following string:

#include <string>
#include <iostream>

std::string escapeSlashes(std::string str) {
    // I have no idea what to do here
    return str;
}

int main () {
    std::string str = "a\b\c\d";

    std::cout << escapeSlashes(str) << "\n";
    // Desired output:
    // a\\b\\c\\d

    return 0;
}

The problem is that I cannot search for \ in the string, because C++ already treats it as an escape sequence.

NOTE: I am not able to change the string str in the first place. It is parsed from a LaTeX file. Thus, this answers to a similar question does not apply.

Aucun commentaire:

Enregistrer un commentaire