C++:字符串索引和保留标点符号时出现问题

C++: Trouble with string indexing and keeping punctuation

本文关键字:问题 标点符号 保留 字符串 索引 C++      更新时间:2023-10-16

所以我有一个函数,它在技术上索引字符串中第一个和最后一个字符之间的字符,打乱内部,然后重新添加第一个和最后一个字母。 它工作正常,直到我意识到带有标点符号的单词会让它变得糟糕。 我希望标点符号保持在同一索引中,关于如何做到这一点的任何想法?

string shuffle_word(string word){
    string scramble_str = "", full_scramble = "";
    if(word.length() > 2){
        scramble_str += word.substr(1, word.length()-2);  //indexes the inside string (excludes first and last char)
        random_shuffle(scramble_str.begin(), scramble_str.end());
        full_scramble = word[0] + scramble_str + word[word.length()-1]; //adds first and last char back on
        return full_scramble;
    }
    else{
        return word;
    }
}

使用与第一个和最后一个字符相同的操作的变体可能是最简单的:

  1. 记录每个标点字符的位置
  2. 提取并保存标点字符
  3. 打乱字母
  4. 在原始位置插入每个标点字符

您可以创建非标点字符的索引列表,然后随机排列索引。然后像这样修改字符串:

    if (numShuffledIndices > 0)
    {
        char temp = word[shuffledIndices[0]]; // save first character
        for (int i = 0; i < numShuffledIndices-1; ++i)
        {
            word[shuffledIndices[i]] = word[shuffledIndices[i+1]];
        }
        word[shuffledIndices[numShuffledIndices-1]] = temp;
    }

因此,如果字符串是"Hello, world!",则索引将为 [0, 1, 2, 3, 4, 7, 8, 9, 10, 11]。如果将它们洗牌为 [7, 4, 2, 9, 1, 0, 11, 8, 3 10],则生成的字符串将是"dHrll, olewo!

我会选择这样的东西:

std::vector<int> punctuatuion_char_indicies = findIndiciesOfPunctuation(input_string);
std::string result = shuffle_word(input_string);

std::vector<int> punctuatuion_char_indicies2 = findIndiciesOfPunctuation(result);


for(int i=0; i< sizeOfPunctuationVectors ; ++i)
{
  std::swap( result[ punctuatuion_char_indicies[i] ], 
             result[ punctuatuion_char_indicies2[i] ); // std::swap is in <algorithm>
}

或者,您可以使用punctuatuion_char_indicies向量分部分执行随机播放功能。