从C ++中的字符串中删除\r [英] Remove \r from a string in C++
问题描述
在C ++程序中,有一点当它读取一个字符串,如:
in a C++ program, there is a point when it reads a string like:
"NONAME_1_1\r"
\r
我猜它打印或添加像^ M。这样对吗?无论如何它给我的问题,我想摆脱它。
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.
我不能修改输入。我不知道我怎么可能在这一点上,使用C + +,并以最简单的方式,删除 \r
这个字符串。
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.
我知道如何在bash上执行此操作,但在C ++上没有任何线索。
I know how to do it on bash but no clue on C++.
推荐答案
我假设通过字符串,你的意思是 std :: string
。
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:
p>
mystring.pop_back();
mystring.erase(mystring.size() - 1);
编辑: pop_back()
有些检查:
if (!mystring.empty() && mystring[mystring.size() - 1] == '\r')
mystring.erase(mystring.size() - 1);
如果您要删除所有 \r
,您可以使用:
If you want to remove all \r
, you can use:
mystring.erase( std::remove(mystring.begin(), mystring.end(), '\r'), mystring.end() );
这篇关于从C ++中的字符串中删除\r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!