尝试编写一个程序来清理字符串。但是由于某种原因,我遇到了双空格问题。它要么只删除一半的多余空间,要么永远运行。
char input[246] = {'\0'};
bool done = false;
int count = 0;
while (!done)
{
cout << "Hello, please enter a string to translate." << endl;
cin.get(input, 246);
}
for (int i = 0; i <= 246; i++)
{
if (input[i] != '\0')
{
count++;
}
}
for (int i = 0; i <= count - 1;) //remove double spaces
{
while (input[i] == ' ' && input[i + 1] == ' ')
{
for (int q = i + 1; q <= (count - 1) - i; q++)
{
input[q] = input[q + 1];
}
count--;
}
else
{
i++;
}
}
最佳答案
您可以使用 std::unique
使用自定义谓词删除重复空格:
auto last = std::unique(&input[0], input + strlen(input), [](char const& a, char const &b)
{
return std::isspace(a) && std::isspace(b);
});
*last = '\0'; // Terminate string
关于c++ - 从 char 数组中删除双空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58407774/