开发者

Remove \r from a string in 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.


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() );


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'.
  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.
  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'.


This is a common problem when reading lines from files after moving them between unix and windows.

  • Unix variants use "\n" (line feed) to terminate lines.
  • Windows uses "\r\n" (carriage return, line feed) to terminate lines.

You can run the "dos2unix" or "unix2dos" to convert lines in a file.


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.

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'; });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜