0

As above, I'm trying to delete two character sub-string (not new-line character, just plain text) from a line.

What I am doing right now is line.replace(line.find("\\n"), 3, ""); because I wanted to escape it, but I receive debug error saying that abort() has been called. Moreover, I am not sure about size 3, because first slash shouldn't be treated as a literal character.

Radoslaw Dubiel
  • 122
  • 2
  • 9

2 Answers2

2

I guess this is exactly what you're looking for:

std::string str = "This is \\n a string \\n containing \\n a lot of \\n stuff.";
const std::string to_erase = "\\n";

// Search for the substring in string
std::size_t pos = str.find(to_erase);
while (pos != std::string::npos) {
    // If found then erase it from string
    str.erase(pos, to_erase.length());
    pos = str.find(to_erase);
}

Note that you're likely getting std::abort because you are passing std::string::npos or the length 3 (not 2) to std::string::replace.

Petr Mánek
  • 1,046
  • 1
  • 9
  • 24
0
#include <iostream>
#include <string>
int main()
{

std::string head = "Hi //nEveryone. //nLets //nsee //nif //nthis //nworks";
std::string sub = "//n";
std::string::iterator itr;
for (itr = head.begin (); itr != head.end (); itr++)
{
  std::size_t found = head.find (sub);
  if (found != std::string::npos)
head.replace (found, sub.length (), "");

}
 std::cout << "after everything = " << head << std::endl;
}

i got the output as :

after everything = Hi Everyone. Lets see if this works