What's the best way to trim std::string?

后端 未结 30 2889
无人及你
无人及你 2020-11-21 22:13

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\\         


        
30条回答
  •  终归单人心
    2020-11-21 22:57

    My answer is an improvement upon the top answer for this post that trims control characters as well as spaces (0-32 and 127 on the ASCII table).

    std::isgraph determines if a character has a graphical representation, so you can use this to alter Evan's answer to remove any character that doesn't have a graphical representation from either side of a string. The result is a much more elegant solution:

    #include 
    #include 
    #include 
    
    /**
     * @brief Left Trim
     *
     * Trims whitespace from the left end of the provided std::string
     *
     * @param[out] s The std::string to trim
     *
     * @return The modified std::string&
     */
    std::string& ltrim(std::string& s) {
      s.erase(s.begin(), std::find_if(s.begin(), s.end(),
        std::ptr_fun(std::isgraph)));
      return s;
    }
    
    /**
     * @brief Right Trim
     *
     * Trims whitespace from the right end of the provided std::string
     *
     * @param[out] s The std::string to trim
     *
     * @return The modified std::string&
     */
    std::string& rtrim(std::string& s) {
      s.erase(std::find_if(s.rbegin(), s.rend(),
        std::ptr_fun(std::isgraph)).base(), s.end());
      return s;
    }
    
    /**
     * @brief Trim
     *
     * Trims whitespace from both ends of the provided std::string
     *
     * @param[out] s The std::string to trim
     *
     * @return The modified std::string&
     */
    std::string& trim(std::string& s) {
      return ltrim(rtrim(s));
    }
    

    Note: Alternatively you should be able to use std::iswgraph if you need support for wide characters, but you will also have to edit this code to enable std::wstring manipulation, which is something that I haven't tested (see the reference page for std::basic_string to explore this option).

提交回复
热议问题