无法清除字符串中的空格

时间:2021-02-10 23:04:22

标签: c++ string trim

假设我有三个这样的字符串

"RES-003 :"
"RES 007 :"
" RES-015      :"

我想让它们看起来像我展示它们的时候

"RES-003:"
"RES 007:"
"RES-015:"

我试图解决这个问题,但是我无法解决这个问题,因为当我尝试清理冒号和数字之间的空格时,我删除了第二个字符串“RES 007 :”中的空格,因此它会发生变化改为“RES007:”。

我的修剪功能看起来像那样。

std::string& Reservation::trim(std::string& s) {
        bool valid = true;
        s.erase(0, s.find_first_not_of(' '));
        s.erase(s.find_last_not_of(' ') + 1);

        while (valid)
        {
            if (s.find("  ") != std::string::npos) {
                s.erase(s.find("  "), 1);
                valid = true;
                if (s.find(" ") != std::string::npos) {
                    s.erase(s.find(" "), 1);
                    valid = true;
                }
            }
            else
                valid = false;
        }

        return s;
    }

我可以做些什么来改进它或者我必须完全替换它?

1 个答案:

答案 0 :(得分:0)

根据您提供的示例,假设您的字符串格式为:

\s*[A-Z]{3}[\s\-][0-9]{3}\s*:\s*

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    auto trimStr = [](const auto& str) -> std::string 
    {
        auto first = std::find_if(str.begin(), str.end(), 
            [](unsigned char c){ return !std::isspace(c); });
        
        return std::string(first, first+7) + ":";
    };

    std::vector<std::string> examples = 
    { 
        "RES-003 :",
        "RES 007 :",
        " RES-015      :"
    };

    for(const auto& elem : examples)
    {
        std::cout << trimStr(elem) << "\n";
    }
}

Godbolt