从字符串中删除前导和尾随空格

新手上路,请多包涵

如何从 C++ 中的字符串对象中删除空格。

例如,如何从下面的字符串对象中删除前导和尾随空格。

 //Original string: "         This is a sample string                    "
//Desired string: "This is a sample string"

据我所知,字符串类没有提供任何删除前导和尾随空格的方法。

为了增加问题,如何扩展此格式以处理字符串单词之间的额外空格。例如,

 // Original string: "          This       is         a sample   string    "
// Desired string:  "This is a sample string"

使用解决方案中提到的字符串方法,我可以考虑分两步进行这些操作。

  1. 删除前导和尾随空格。
  2. 在单词边界处重复使用 find_first_of、find_last_of、find_first_not_of、find_last_not_of 和 substr 以获得所需的格式。

原文由 TL36 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 543
2 个回答

这称为修剪。如果您可以使用 Boost ,我会推荐它。

否则,使用 find_first_not_of 获取第一个非空格字符的索引,然后使用 find_last_not_of 从末尾获取非空格的索引。有了这些,使用 substr 来获取没有周围空格的子字符串。

作为对您的编辑的回应,我不知道该术语,但我猜想类似于“减少”的内容,所以这就是我所说的。 :) (注意,为了灵活性,我已将空格更改为参数)

 #include <iostream>
#include <string>

std::string trim(const std::string& str,
                 const std::string& whitespace = " \t")
{
    const auto strBegin = str.find_first_not_of(whitespace);
    if (strBegin == std::string::npos)
        return ""; // no content

    const auto strEnd = str.find_last_not_of(whitespace);
    const auto strRange = strEnd - strBegin + 1;

    return str.substr(strBegin, strRange);
}

std::string reduce(const std::string& str,
                   const std::string& fill = " ",
                   const std::string& whitespace = " \t")
{
    // trim first
    auto result = trim(str, whitespace);

    // replace sub ranges
    auto beginSpace = result.find_first_of(whitespace);
    while (beginSpace != std::string::npos)
    {
        const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
        const auto range = endSpace - beginSpace;

        result.replace(beginSpace, range, fill);

        const auto newStart = beginSpace + fill.length();
        beginSpace = result.find_first_of(whitespace, newStart);
    }

    return result;
}

int main(void)
{
    const std::string foo = "    too much\t   \tspace\t\t\t  ";
    const std::string bar = "one\ntwo";

    std::cout << "[" << trim(foo) << "]" << std::endl;
    std::cout << "[" << reduce(foo) << "]" << std::endl;
    std::cout << "[" << reduce(foo, "-") << "]" << std::endl;

    std::cout << "[" << trim(bar) << "]" << std::endl;
}

结果:

 [too much               space]
[too much space]
[too-much-space]
[one
two]

原文由 GManNickG 发布,翻译遵循 CC BY-SA 4.0 许可协议

去除前导和尾随空格的恒定时间和空间复杂度可以通过在字符串中使用 pop_back() 函数来实现。代码如下所示:

 void trimTrailingSpaces(string& s) {
    while (s.size() > 0 && s.back() == ' ') {
        s.pop_back();
    }
}

void trimSpaces(string& s) {
    //trim trailing spaces.
    trimTrailingSpaces(s);
    //trim leading spaces
    //To reduce complexity, reversing and removing trailing spaces
    //and again reversing back
    reverse(s.begin(), s.end());
    trimTrailingSpaces(s);
    reverse(s.begin(), s.end());
}

原文由 BishalG 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题