我是初学者编码器,我已经查询并研究了如何将多个空格移到单个空间但我不明白每个算法的意图。我也尝试在emacs中将我们的算法实现到我的程序中,但是当我调试它们时,我收到的都是错误。
我已经调查过了 Interview Question : Trim multiple consecutive spaces from a string和 Replace multiple spaces with one space in a string 但我没有成功。
图像显示了我想要做的事情。取cin和cout之间的空格并将它们转换成一个。 enter image description here 我已经编码了除多个空格以外的所有内容。
如果有人能够清楚地解释我是如何做到的,那将非常感激!
答案 0 :(得分:0)
<强> 1。使用string
方法的最简单的解决方案:
string str = " many spaces ";
while(true)
{
// find the starting position of two consecutive space characters
unsigned int pos = str.find(" ");
// if str.find does not find two consecutive spaces, it will return string::npos
if(pos == string::npos) // no more consecutive spaces
{
break;
}
else // found two consecutive spaces
{
// erase one space
str.erase(pos, 1);
}
}
<强> 2。不使用string
方法的解决方案(高级):
char charArray[] = " many spaces ";
int write_index = 1;
if(sizeof(charArray) > 1) // the check starts at position 1 because we need to check if the previous character too (if it is a space)
{
// repeat until the reading index reaches the end of the character array
for(int read_index=1; read_index!=sizeof(charArray); ++read_index)
{
// if the current character or the previous character is not a space
if(charArray[read_index] != ' ' || charArray[read_index-1] != ' ')
{
// then write the character
charArray[write_index] = charArray[read_index];
++write_index;
}
}
}
请注意,charArray
此处必须是以空字符结尾的字符序列,这意味着最后一个字符为'\0'
或整数值为0
。在覆盖数组的一部分之后,我们不会删除数组末尾的任何字符。但是我们正在将0
字符从最后复制到另一个位置。
示例(此处的N标记空字符的位置):
// array in the beginning:
" many spaces N"
// after all replaces:
" many spaces Npaces N"
从修改后的数组中调用cout
或构造string
类型将提供所需的结果,因为空字符后面的所有内容都将被剪裁。
但是,如果要在空字符后完全删除数组中的字符,则必须创建一个大小为write_index
的新数组,并复制charArray
中的字符。
这种方法的工作原理在&#34;采访问题&#34;帖子的答案。我会解释一下:
我们有两个索引:read_index
和write_index
。
read_index
在循环的每次迭代中递增,它确定我们正在检查的数组中字符的位置。
write_index
仅在字符被&#34;保存&#34;时才会增加,并且保存我的意思是覆盖我们之前已经检查过的字符。
从代码中可以看出,一个角色被保存了#34;只有它不是另一个空间之后的空间。因此,每当我们在数组中找到空格时,如果前一个字符不是空格,我们仍然会保存它。但是如果前一个字符也是一个空格(因此已经保存了),我们就跳过它。因此,我们在结束数组中最多只有一个连续的空格(仅考虑第一个空字符之前的字符,当然)。