Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove \r from a string in C++

Tags:

c++

in a C++ program, there is a point when it reads a string like:

"NONAME_1_1\r"

the \r is causing me trouble. I guess it prints or adds something like "^M". Is it right? Anyway it casues me problem, and I want to get rid of it.

I can not modify the input. I wonder how could I at this point, using C++, and in the easiest way, to remove \r for this string.

I know how to do it on bash but no clue on C++.

Thanks.

like image 875
Open the way Avatar asked Mar 27 '10 10:03

Open the way


People also ask

How do I remove RN from text?

Try this. text = text . Replace("\\r\\n", "");

How do I remove a string from a string in R?

You can either use R base function gsub() or use str_replace() from stringr package to remove characters from a string or text.


1 Answers

I'm assuming that by string, you mean std::string.

If it's only the last character of the string that needs removing you can do:

mystring.pop_back();

mystring.erase(mystring.size() - 1);

Edit: pop_back() is the next version of C++, sorry.

With some checking:

if (!mystring.empty() && mystring[mystring.size() - 1] == '\r')
    mystring.erase(mystring.size() - 1);

If you want to remove all \r, you can use:

mystring.erase( std::remove(mystring.begin(), mystring.end(), '\r'), mystring.end() );
like image 77
CB Bailey Avatar answered Sep 22 '22 17:09

CB Bailey