在c++字符串中插入空格以分隔偶数字符集
Insert spaces to break up even sets of characters within a C++ String
我正试图编写一个函数,该函数将在字符串中找到任何偶数字符子集,并通过在字符串中插入空白空间将它们分成两半。例如,给定字符串"AA BBB CCDD",我的字符串应该转换为"AA BBB CCDD"。
我的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;
}
你说它不起作用,但你没有说为什么不起作用。我可以立即看到两个问题:第一个是当你找到第一个时,你会立即返回单词的长度是均匀的,所以你显然不会破坏任何后续内容单词;第二个是如果你想继续,insert
将会改变它之后任何位置的值。
(fww:我可能会先把整个字符串分解成单词,把它们放在std::vector<std::string>
中,然后迭代,在需要的地方插入额外的空间,然后重新组装它们。这是可能比你现在用的方法慢一点,但已经好多了)
while循环中有一个返回值,因此在第一次插入之后,它将退出函数
void breakString(string &str1){
string::size_type pos1 = 0;
string::size_type pos2 = str1.find_first_of(" ");
while (pos2 != string::npos){
if((pos2 - pos1) % 2 == 0){
str1.insert(pos1 + (pos2-pos1)/2, 1, ' ');
pos2 += 1;
}
pos1 = str1.find_first_not_of(" ", pos2);
pos2 = str1.find_first_of(" ", pos1);
}
if((str1.size() - pos1) % 2 == 0)
str1.insert(pos1 + (str1.size() - pos1)/2, 1, ' ');
return;
}
相关文章:
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 分隔整数 (C++) 的数字
- 如何从文件中读取用空格分隔的数字
- C ++正则表达式允许用点分隔的数字
- 读取以逗号分隔的数字,并将其写入以制表符分隔的文件
- C++ 从文件中读取 int,每个数字用逗号分隔
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何从逗号分隔的数字对中填充 2 个向量 C++.
- 为什么我可以在 C++ 中用撇号分隔数字,但不能用 C 分隔数字
- 用字符分隔数字
- 逗号分隔的数字在模拟器上正确显示,但在iPad上没有显示
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- 给定分隔成数组元素的数字,如何在 int 中重新组合数字
- 如果字符串中没有空格,如何解析带有数字和字符的字符串并分隔数字和字符
- 扫描以空格分隔的数字
- 解析逗号分隔的数字(C++)
- C++ - 如何将空格分隔的数字输入数组
- 递增由不同分隔符分隔的字符数组中的数字
- 解析来自 getline 的空格分隔数字
- 如何在C或c++代码中分隔数字常量(例如10,000)中的数字