【发布时间】:2021-02-11 07:58:49
【问题描述】:
我有这个来自网上的代码 sn-p。
void ShortenSpace(string &s)
{
// n is length of the original string
int n = s.length();
//pointer i to keep trackof next position and j to traverse
int i = 0, j = -1;
// flag that sets to true is space is found
bool spaceFound = false;
// Handles leading spaces
while (++j < n && s[j] == ' ');
// read all characters of original string
while (j < n)
{
// if current characters is non-space
if (s[j] != ' ')
{
//if any preceeding space before ,.and ?
if ((s[j] == '.' || s[j] == ',' ||
s[j] == '?') && i - 1 >= 0 &&
s[i - 1] == ' ')
s[i - 1] = s[j++];
else
// copy current character to index i
// and increment both i and j
s[i++] = s[j++];
// set space flag to false when any
// non-space character is found
spaceFound = false;
}
// if current character is a space
else if (s[j++] == ' ')
{
// If space is seen first time after a word
if (!spaceFound)
{
s[i++] = ' ';
spaceFound = true;
}
}
}
// Remove trailing spaces
if (i <= 1)
s.erase(s.begin() + i, s.end());
else
s.erase(s.begin() + i - 1, s.end());
}
问题是如果输入是:“test(多个空格)test(多个空格)test。”
它将删除最后一个句点并像“test test test”一样输出
它正确地删除了空格,但不知何故它处理不当/删除了标点符号。我不希望它删除标点符号。我还是 C++ 的初学者,所以我很难弄清楚为什么。
【问题讨论】:
-
提示:这是一个学习如何使用调试器的好用例:单步调试代码,检查每个字符发生的情况。
-
并留意意外情况。意外是程序中的错误或您的期望。要么不好。
-
使用调试器(或者如果太复杂,可以考虑打印中间值)。要问自己的一个问题是,当您遇到“.”时会发生什么
标签: c++ string whitespace