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

后端 未结 30 2892
无人及你
无人及你 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:41

    Contributing my solution to the noise. trim defaults to creating a new string and returning the modified one while trim_in_place modifies the string passed to it. The trim function supports c++11 move semantics.

    #include 
    
    // modifies input string, returns input
    
    std::string& trim_left_in_place(std::string& str) {
        size_t i = 0;
        while(i < str.size() && isspace(str[i])) { ++i; };
        return str.erase(0, i);
    }
    
    std::string& trim_right_in_place(std::string& str) {
        size_t i = str.size();
        while(i > 0 && isspace(str[i - 1])) { --i; };
        return str.erase(i, str.size());
    }
    
    std::string& trim_in_place(std::string& str) {
        return trim_left_in_place(trim_right_in_place(str));
    }
    
    // returns newly created strings
    
    std::string trim_right(std::string str) {
        return trim_right_in_place(str);
    }
    
    std::string trim_left(std::string str) {
        return trim_left_in_place(str);
    }
    
    std::string trim(std::string str) {
        return trim_left_in_place(trim_right_in_place(str));
    }
    
    #include 
    
    int main() {
    
        std::string s1(" \t\r\n  ");
        std::string s2("  \r\nc");
        std::string s3("c \t");
        std::string s4("  \rc ");
    
        assert(trim(s1) == "");
        assert(trim(s2) == "c");
        assert(trim(s3) == "c");
        assert(trim(s4) == "c");
    
        assert(s1 == " \t\r\n  ");
        assert(s2 == "  \r\nc");
        assert(s3 == "c \t");
        assert(s4 == "  \rc ");
    
        assert(trim_in_place(s1) == "");
        assert(trim_in_place(s2) == "c");
        assert(trim_in_place(s3) == "c");
        assert(trim_in_place(s4) == "c");
    
        assert(s1 == "");
        assert(s2 == "c");
        assert(s3 == "c");
        assert(s4 == "c");  
    }
    

提交回复
热议问题