在C 中的单词之间删除除一个空间以外的所有空间

Removing all but one whitespace between words in C++

本文关键字:空间 一个 单词 之间 删除      更新时间:2023-10-16

我需要在单词之间删除除一个空白以外的所有空间。在进入下一个单词之前,我仔细阅读了字符串和if (temp.back() == ' ' && c != ' ')。但它删除了所有白色空间。任何提示问题在哪里?

string removeWhiteSpace(string current)
{
  string myNewString = "";
  string temp = "";
  for (char c : current)
  {
    temp.push_back(c);
    if (temp.back() == ' ' && c != ' ')
    {
      myNewString.push_back(' ');
    }
    if (c != ' ')
    {
      myNewString.push_back(c);
    }
  }
  return myNewString;
}

问题在条件

if (temp.back() == ' ' && c != ' ')

如果最后一个字符不是空间,则要添加空间,而c是一个空间:

if (temp.back() != ' ' && c == ' ')

(您逆转了==!=操作员)。

此外,您还需要在此条件块之后推动新角色c(否则temp.back()c始终是同一字符)。

最后,在开始字符串temp是空的,不允许调用back(),您应该使用非空白初始化它(例如temp = "x")。

因此,有效的最终功能是:

string removeWhiteSpace(string current)
{
  string myNewString = "";
  string temp = "x";
  for (char c : current)
  {
    if (temp.back() != ' ' && c == ' ')
    {
      myNewString.push_back(' ');
    }
    temp.push_back(c);
    if (c != ' ')
    {
      myNewString.push_back(c);
    }
  }
  return myNewString;
}

您可能想删除额外的空格。此代码将有所帮助。

string removeWhiteSpace(string current)
{
  string myNewString = "";
  string temp = "";
  int l=current.length();
  myNewString+=current[0];
  for(int i=1;i<l;i++){
      if(myNewString[myNewString.length()-1]==' ' && current[i]==' ')
          continue;
      else
          myNewString+=current[i];
  }
  return myNewString;
}

一个更多的C ISH解决方案:

#include <algorithm>
#include <cctype>
#include <string>
#include <utility>
#include <iostream>
std::string remove_excessive_ws(std::string str)
{
    bool seen_space = false;
    auto end{ std::remove_if(str.begin(), str.end(),
                             [&seen_space](unsigned ch) {
                                 bool is_space = std::isspace(ch);
                                 std::swap(seen_space, is_space);
                                 return seen_space && is_space;
                             }
              )
    };
    if (end != str.begin() && std::isspace(static_cast<unsigned>(end[-1])))
        --end;
    str.erase(end, str.end());
    return str;
}
int main()
{
    char const *foo{ "Hello              World!       " };
    std::cout << '"' << remove_excessive_ws(foo) << ""n";
}

输出:

"Hello World!"
相关文章: