在C 中的单词之间删除除一个空间以外的所有空间
Removing all but one whitespace between words in C++
我需要在单词之间删除除一个空白以外的所有空间。在进入下一个单词之前,我仔细阅读了字符串和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!"
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- '使用命名空间{嵌套在另一个命名空间中的某个命名空间}"
- 使用另一个命名空间中的函数C++
- 使用命名空间在另一个".cpp"文件中定义
- 是否可以在专用内存空间中分配一个为提升管理共享内存而创建的对象
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- C ++使用getline,输出在开头带有一个额外的空间
- 如何使用另一个项目命名空间?
- 使用匿名命名空间中的函数或另一个文件中的静态函数不应该出错吗?
- 在模板参数的函数中使用一个命名空间或另一个命名空间
- 由另一个对象重用对象的空间
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 在同一C 源文件中使用多个名称空间是一个好习惯吗?
- C++另一个命名空间中函数的 ADL
- 如何在另一个名称空间内从另一个命名空间内明确专业化功能模板
- 我可以在标头中将一个命名空间"import"到另一个命名空间中吗?
- ptrA = ptrB 是否等同于 ptrA = &*ptrB?,空值是否共享一个地址空间?
- 我可以定义一个(键入的)常数,该常数确定不占据可执行文件中的空间
- 在C 的COUT系列中创建一个空间
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?