std::stringをトリム

#include <string>

using std::string;

string trim(const string& str)
{
    string::const_iterator top, tail;
    top  = str.begin();
    tail = str.end();

    while (isspace(*top)  && (top != str.end()))    top++;
    while (isspace(*tail) && (tail != str.begin())) tail--;

    return string(top, tail);
}

文字列の後がトリムされない...うーむと悩んだら、end()が返すイテレータが文字列端のNULL文字列の向こう側ににあったので、tailが文字列端を指したとたんにisspace(*tail)がいきなりfalseを返していたのね。ちうことで、回転する前に、一度tailを一つ下げて下げてあげる必要があるわけだが、いまいち綺麗じゃないな・・・。

tail = str.end() - 1;