0

I ask this because I am using SFML strings. sf::String does not insert a new line in the presence of a \n.

I can't seem to figure out a way without using 3/4 STL algorithms.

std::replace_if(str.begin(), str.end(), [](const char&c](return c == '\\n'), '\n'}); does not work. The string remains the same.

I have also tried replacing the \\ occurrence with a temporary, say ~. This works, but when I go to replace the ~ with \, then it adds a \\ instead of a \

I have produced a solution by manually replacing and deleting duplicates after \n insertion :

for (auto it = str.begin(); it != str.end(); ++it) {
    if (*it == '\\') {
        if (it + 1 != str.end()) {
            if (*(it + 1) != 'n') continue;
            *it = '\n';
            str.erase(it + 1);
        }
    }
}
expl0it3r
  • 325
  • 1
  • 7

2 Answers2

3

You might do:

str = std::regex_replace(str, std::regex(R"(\\n)"), "\n")

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • My compiler does not let me do this. I get an error for some reason? – expl0it3r Aug 18 '20 at 00:45
  • 3
    All of this back-and-forth could be reduced immensely by asking the right question: include a [mcve] in your question (it should be like 5 lines long!), mention what compiler you're using and IDE. There's no set rule on what version of C++ people who answer questions use, though it's typically _at least_ C++11 (which is 10 years old). If you only have support for an older version like C++03 you should specify – Tas Aug 18 '20 at 00:47
  • Added demo link and a "typo". – Jarod42 Aug 18 '20 at 00:47
1

The problem is that '\\n' is not a single character but two characters. So it needs to be stored in a string "\\n". But now std::replace_if doesn't work because it operates on elements and the elements of a std::string are single characters.

You can write a new function to replace sub-strings within a string and call that instead. For example:

std::string& replace_all(std::string& s, std::string const& from, std::string const& to)
{
    if(!from.empty())
        for(std::string::size_type pos = 0; (pos = s.find(from, pos) + 1); pos += to.size())
            s.replace(--pos, from.size(), to);
    return s;
}

// ...

std::string s = "a\\nb\\nc";

std::cout << s << '\n';

replace_all(s, "\\n", "\n");

std::cout << s << '\n';
Galik
  • 47,303
  • 4
  • 80
  • 117
  • 2
    It might be two characters `{'\\', 'n'}`... it might be three characters `{'\\', '\\', 'n'}` ... hard to say for sure. – Eljay Aug 18 '20 at 01:09