插入空格以分隔 C++ 中的偶数字符集。细绳
我正在尝试编写一个函数,该函数将找到字符串中的任何偶数字符子集,并通过在字符串中插入空格将它们分成两半。例如,给定字符串“AA BBB CCDD”,我的字符串应转换为“AA BBB CC DD”。
我的breakString()函数似乎不起作用,我不知道为什么。有人可以帮忙吗?
void breakString(string &str1)
{
int pos1 = -1;
int pos2 = str1.find_first_of(" ", pos1+1);
while (pos2 != -1)
{
if(((pos2-pos1)-1)%2 == 0)
{
str1.insert((pos2-pos1)/2, 1, ' ');
return;
}
else
{
pos1 = pos2;
pos2 = str1.find_first_of(' ', pos1+1);
}
}
if((str1.size() - pos1)%2 == 1)
str1.insert((str1.length()-pos1)/2, 1, ' ');
return;
}
I am trying to write a function that will find any even subsets of characters in a string, and break them in half by inserting an empty space into the string. For example, given the string "AA BBB CCDD", my string should be converted to "A A BBB CC DD".
My breakString() function doesn't seem to work, and I have no idea why. Can anyone help?
void breakString(string &str1)
{
int pos1 = -1;
int pos2 = str1.find_first_of(" ", pos1+1);
while (pos2 != -1)
{
if(((pos2-pos1)-1)%2 == 0)
{
str1.insert((pos2-pos1)/2, 1, ' ');
return;
}
else
{
pos1 = pos2;
pos2 = str1.find_first_of(' ', pos1+1);
}
}
if((str1.size() - pos1)%2 == 1)
str1.insert((str1.length()-pos1)/2, 1, ' ');
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你说不行,但没说怎么办。我可以立即看到两个
问题:第一个是找到第一个就立即返回
单词长度均匀,因此显然不会破坏任何后续内容
字;第二个是,如果您确实想继续,则
插入
将更改其后任何位置的值。
(FWIW:我可能会先将整个字符串分解成单词,
将它们放入
std::vector
中,然后对其进行迭代,在需要的地方插入额外的空间,然后重新组装。它是
可能比您使用的方法慢一点,但是很多
更干净、更容易遵循。)
You say it doesn't work, but you don't say how. I can see two immediate
prblems: the first is that you return immediatly when you find the first
word with an even length, so you obviously won't break any following
words; and the second is that if you do want to continue, the
insert
will have changed the values of any position after it.
(FWIW: I'd probably break the entire string down into words first,
putting them in an
std::vector<std::string>
, then iterate on that,inserting the extra space where needed, then reassemble them. It's
probably a bit slower than the approach you're using, but it's a lot
cleaner and easier to follow.)
while 循环中有一个 return,因此在第一次插入后,它将退出该函数。
You have a return in your while-loop, so after the first insertion, it will exit the function.