[英]Remove \r from a string in C++
in a C++ program, there is a point when it reads a string like: 在C ++程序中,有一点是它读取一个字符串,如:
"NONAME_1_1\r"
the \\r
is causing me trouble. \\r
给我带来了麻烦。 I guess it prints or adds something like "^M". 我想它打印或添加类似“^ 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. 我想我怎么能在这一点上使用C ++,以最简单的方式,为这个字符串删除
\\r
。
I know how to do it on bash but no clue on C++. 我知道如何在bash上做到这一点,但对C ++没有任何线索。
Thanks. 谢谢。
I'm assuming that by string, you mean std::string
. 我假设通过字符串,你的意思是
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. 编辑:
pop_back()
是C ++的下一个版本,抱歉。
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: 如果要删除所有
\\r
,您可以使用:
mystring.erase( std::remove(mystring.begin(), mystring.end(), '\r'), mystring.end() );
That depends on how you are holding it in memory: 这取决于你如何将它保存在内存中:
'\\r'
. '\\r'
。 '\\r'
with '\\0'
. '\\r'
替换为'\\0'
。 This is a common problem when reading lines from files after moving them between unix and windows. 在unix和windows之间移动文件后从文件中读取行时,这是一个常见问题。
You can run the "dos2unix" or "unix2dos" to convert lines in a file. 您可以运行“dos2unix”或“unix2dos”来转换文件中的行。
copy_if is useful if you want to leave the original string untouched and also if you want to want remove multiple characters like CR & LF in this example. 如果您希望保持原始字符串不变,并且您希望在此示例中删除多个字符(如CR和LF),则copy_if非常有用。
const std::string input = "Hello\r\nWorld\r\n";
std::string output;
output.reserve(input.length());
std::copy_if(input.begin(), input.end(),
std::back_inserter(output),
[] (char c) { return c != '\r' && c != '\n'; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.