所以我有一个函数,可以从技术上对字符串中第一个字符和最后一个字符之间的字符进行索引,在内部打乱,然后重新添加第一个和最后一个字母。它工作正常,直到我意识到带有标点符号的单词使它变得古怪。我希望标点符号保留在同一个索引中,关于如何去做的任何想法?
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;
}
}
最佳答案
使用您对第一个和最后一个字符所做的相同操作的变体可能是最简单的:
- 记录每个标点符号的位置
- 提取并保存标点符号
- 打乱字母
- 在其原始位置插入每个标点符号
关于C++:字符串索引和保留标点符号的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327634/