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

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

    I guess if you start asking for the "best way" to trim a string, I'd say a good implementation would be one that:

    1. Doesn't allocate temporary strings
    2. Has overloads for in-place trim and copy trim
    3. Can be easily customized to accept different validation sequences / logic

    Obviously there are too many different ways to approach this and it definitely depends on what you actually need. However, the C standard library still has some very useful functions in , like memchr. There's a reason why C is still regarded as the best language for IO - its stdlib is pure efficiency.

    inline const char* trim_start(const char* str)
    {
        while (memchr(" \t\n\r", *str, 4))  ++str;
        return str;
    }
    inline const char* trim_end(const char* end)
    {
        while (memchr(" \t\n\r", end[-1], 4)) --end;
        return end;
    }
    inline std::string trim(const char* buffer, int len) // trim a buffer (input?)
    {
        return std::string(trim_start(buffer), trim_end(buffer + len));
    }
    inline void trim_inplace(std::string& str)
    {
        str.assign(trim_start(str.c_str()),
            trim_end(str.c_str() + str.length()));
    }
    
    int main()
    {
        char str [] = "\t \nhello\r \t \n";
    
        string trimmed = trim(str, strlen(str));
        cout << "'" << trimmed << "'" << endl;
    
        system("pause");
        return 0;
    }
    

提交回复
热议问题