代码之家  ›  专栏  ›  技术社区  ›  Xolve

为什么我的修剪功能不起作用?

  •  1
  • Xolve  · 技术社区  · 15 年前
    void trim(string &str)
    {
        string::iterator it = str.begin();
        string::iterator end = str.end() - 1;
    
        // trim at the starting
        for(; it != str.end() && isspace(*it); it++)
            ;
        str.replace(str.begin(), it, "");
    
        // trim at the end
        for(; end >= str.begin() && isspace(*end); end--)
            ;
        str.replace(str.end(), end, ""); // i get the out_of_range exception here
    }
    

    为什么?

    5 回复  |  直到 15 年前
        1
  •  7
  •   perreal    14 年前

    更改字符串

    void trim(std::string &str)
    {
        std::string::size_type begin=0;
        while(begin<str.size() && isspace(str[begin]))
          ++begin;
        std::string::size_type end=str.size()-1;
        while(end>begin && isspace(str[end]))
          --end;
        str = str.substr(begin, end - begin + 1)
    }
    
        2
  •  3
  •   Pieter    15 年前

    我建议使用 boost::trim

        3
  •  2
  •   sharptooth    15 年前

    迭代器只有在您修改字符串之前才确定有效。一旦您更改了字符串,结束迭代器肯定会失效。

        4
  •  0
  •   UncleBens    15 年前

    问题是,您将迭代器存储到字符串中的最后一个字符,并且仅在(可能)从字符串中删除字符后才使用它,因此存储的迭代器现在无效(不再指向最后一个字符)。

    因此,在删除前导空格之后初始化结束迭代器。(也可以考虑先删除尾随空格。)


    我也可以建议使用 erase

    删除尾随空格时可能会有其他错误,但您可以在到达那里时找到它。

        5
  •  -1
  •   Milind Ganjoo    15 年前