【问题标题】:Having trouble cleaning out spaces in a string无法清除字符串中的空格
【发布时间】:2021-02-10 23:04:22
【问题描述】:

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

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

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

【问题讨论】:

  • 如果你知道字符串的格式,即3个字符连字符3个数字空格冒号,然后找到第一个非空格字符,将接下来的7读入一个新字符串。
  • 从头到尾修剪空格。将所有多空格修剪为单个空格。将空格冒号修剪为冒号。砰,完成。
  • @Eljay 好主意。谢谢!

标签: c++ string trim


【解决方案1】:

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

\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

【讨论】:

  • 在生产代码中,永远不应该假设格式总是正确的。因此firstfirst+7 应该被验证(可能还有两者之间的内容)。
  • @Phil1970 我同意,绝对不是生产质量,只是一个修剪字符串的简单示例。
猜你喜欢
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
相关资源
最近更新 更多