在c++字符串中插入空格以分隔偶数字符集

Insert spaces to break up even sets of characters within a C++ String

本文关键字:分隔 数字 字符集 空格 c++ 字符串 插入      更新时间:2023-10-16

我正试图编写一个函数,该函数将在字符串中找到任何偶数字符子集,并通过在字符串中插入空白空间将它们分成两半。例如,给定字符串"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;
}