开发者

Trimming white spaces/converting iterators

I wanted to write two one-line functions which will trim white spaces from left and right side of a string. Left side weren't problem:

void trimLeft(string &s) {
  s.erase(s.begin(), find_if(s.begin(), s.end(), (int (*)(int))isgraph));
}

But when I tried someth开发者_StackOverflowing similar for right side:

void trimRight(string &s) {
  s.erase(find_if(s.rbegin(), s.rend(), (int (*)(int))isgraph), s.end());
}

I had some compiler errors. The problem is that I must convert reverse_iterator (which is returned by find_if) to normal iterator. How to do this?


You can use the base() member function to recover the underlying iterator from its reverse_iterator.

void trimRight(string &s) {
  s.erase(find_if(s.rbegin(), s.rend(), (int (*)(int))isgraph).base(), s.end());
}


Looking at the documentation, it seems like string::erase should take reverse_iterators just fine. The problem is that you're mixing reverse and forward iterators. So try

void trimRight(string &s) {
  s.erase(s.rbegin(), find_if(s.rbegin(), s.rend(), (int (*)(int))isgraph));
}

Edit: Nope.


Use boost::trim?

http://www.boost.org/doc/libs/1_47_0/doc/html/string_algo/usage.html#id2895820

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜