开发者

Trimming white spaces/converting iterators

开发者 https://www.devze.com 2023-04-12 05:32 出处:网络
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:

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

精彩评论

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