所以我有一个函数,它在技术上索引字符串中第一个和最后一个字符之间的字符,在内部打乱,然后将第一个和最后一个字母加回去。它工作得很好,直到我意识到带有标点符号的单词会让它变得扭曲。我希望标点符号保持在相同的索引中,有什么想法可以这样做吗?
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;
}
}发布于 2013-10-12 05:52:09
使用第一个和最后一个字符所做的相同操作的变体可能是最简单的:
记录每个标点符号的位置并将标点符号保存到character
发布于 2013-10-12 05:58:52
您可以创建一个非标点符号的索引列表,然后对索引进行混洗。然后像这样改革字符串:
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!“
发布于 2013-10-12 06:12:38
我会选择这样的东西:
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矢量在各个部分中执行随机播放功能。
https://stackoverflow.com/questions/19327634
复制相似问题