ℙℕℤℝ 2008-10-19 19:23
浏览 622

修剪 std: : string 的最佳方法是什么?

I'm currently using the following code to right-trim all the std::strings in my programs:

std::string s;
s.erase(s.find_last_not_of(" \n\r\t")+1);

It works fine, but I wonder if there are some end-cases where it might fail?

Of course, answers with elegant alternatives and also left-trim solution are welcome.

转载于:https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring

  • 写回答

28条回答 默认 最新

  • 乱世@小熊 2008-10-19 19:55
    关注

    Using Boost's string algorithms would be easiest:

    #include <boost/algorithm/string.hpp>
    
    std::string str("hello world! ");
    boost::trim_right(str);
    

    str is now "hello world!". There's also trim_left and trim, which trims both sides.


    If you add _copy suffix to any of above function names e.g. trim_copy, the function will return a trimmed copy of the string instead of modifying it through a reference.

    If you add _if suffix to any of above function names e.g. trim_copy_if, you can trim all characters satisfying your custom predicate, as opposed to just whitespaces.

    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作