简体   繁体   English

从C ++中的字符串中删除\\ r \\ n

[英]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: 这取决于你如何将它保存在内存中:

  1. If it's in a std::string, just check the last byte and remove it if it's a '\\r' . 如果它在std :: string中,只需检查最后一个字节并删除它,如果它是'\\r'
  2. If it's in a const char*, you can use strncpy to copy the string into another char array, conditionally grabbing the last byte. 如果它在const char *中,你可以使用strncpy将字符串复制到另一个char数组中,有条件地抓取最后一个字节。
  3. If, by "I can not modify the input," you simply mean that you can't touch the source file, then you may have the option to read it into a char array and replace any trailing '\\r' with '\\0' . 如果通过“我无法修改输入”,您只是意味着您无法触摸源文件,那么您可以选择将其读入char数组并将任何尾随的'\\r'替换为'\\0'

This is a common problem when reading lines from files after moving them between unix and windows. 在unix和windows之间移动文件后从文件中读取行时,这是一个常见问题。

  • Unix variants use "\\n" (line feed) to terminate lines. Unix变体使用“\\ n”(换行符)来终止行。
  • Windows uses "\\r\\n" (carriage return, line feed) to terminate lines. Windows使用“\\ r \\ n”(回车,换行)来终止行。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM