天天看點

錯誤的trim和正确的trim(C++)

trim函數用來去除一個字元串左右兩邊的空格和制表符

err例一–>一個錯誤的trim函數展示

string LaStrUtils::trim(const std::string& str)
{
    string ret;
    //find the first position of not start with space or '\t'
    string::size_type pos1 = str.find_first_not_of(" ");
    string::size_type pos2 = str.find_first_not_of('\t');
    string::size_type pos_begin = pos1>pos2?pos1:pos2;
    if(pos_begin == string::npos)
    {
         return str;
    }

    //find the last position of end with space or '\t'
    string::size_type pos3 = str.find_last_of(" ");
    string::size_type pos4 = str.find_last_of('\t');
    string::size_type pos_end = pos3<pos4?pos3:pos4;
    if(pos_end != string::npos)
    {
        ret = str.substr(pos_begin, pos_end - pos_begin);
    }
    ret = str.substr(pos_begin);
    return ret;
}
           

測試樣例

錯誤的trim和正确的trim(C++)

測試結果

錯誤的trim和正确的trim(C++)

沒有考慮space和’\t’的嵌套

err例二–>使用RE(正規表達式)重整代碼

錯誤的trim函數

bool LAStrUtils::trim(const std::string& line, std::string& ret)
{
    regex_t pkg_line_regex;
    //char* pkg_line_pattern = "[ |\t]*([\\+|-][a-zA-Z0-9\\+-_ ]+)[ |\t]*";
    char* pkg_line_pattern = "[ |\t]*([a-zA-Z0-9\\+-_ ]+)[ |\t]*";
    if(regcomp(&pkg_line_regex, pkg_line_pattern, REG_EXTENDED))
    {
        regfree(&pkg_line_regex);
        return false;
    }

    regmatch_t match[];
    if(regexec(&pkg_line_regex, line.c_str(), , match, ))
    {
        return false;
    }

    ret.assign(line.c_str() + match[].rm_so, match[].rm_eo - match[].rm_so);
    return true;
}
           

用” \t aa bb cc \t “測試,最終結果是aa

沒有其他輸出結果了!!

正确的trim函數

最終我選擇老老實實用string類

string LaStrUtils::trim(const std::string& str)
{
    string ret;
    //find the first position of not start with space or '\t'
    string::size_type pos_begin = str.find_first_not_of(" \t");
    if(pos_begin == string::npos)
        return str;

    //find the last position of end with space or '\t'
    string::size_type pos_end = str.find_last_not_of(" \t");
    if(pos_end == string::npos)
        return str;

    ret = str.substr(pos_begin, pos_end-pos_begin);

    return ret;
}
           

達到了我要的目的,下圖為測試樣例以及測試結果,perfect!

錯誤的trim和正确的trim(C++)
錯誤的trim和正确的trim(C++)

大功告成!

繼續閱讀