首页 > 解决方案 > 无法清除字符串中的空格

问题描述

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

"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;
    }

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

标签: c++stringtrim

解决方案


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

\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";
    }
}

神螺栓


推荐阅读