C++:字符串索引和保留标点符号时出现问题
C++: Trouble with string indexing and keeping punctuation
所以我有一个函数,它在技术上索引字符串中第一个和最后一个字符之间的字符,打乱内部,然后重新添加第一个和最后一个字母。 它工作正常,直到我意识到带有标点符号的单词会让它变得糟糕。 我希望标点符号保持在同一索引中,关于如何做到这一点的任何想法?
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;
}
}
使用与第一个和最后一个字符相同的操作的变体可能是最简单的:
- 记录每个标点字符的位置
- 提取并保存标点字符
- 打乱字母
- 在原始位置插入每个标点字符
您可以创建非标点字符的索引列表,然后随机排列索引。然后像这样修改字符串:
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向量分部分执行随机播放功能。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 删除标点符号和空间的问题
- 提升::精神::lex - 标点符号的问题
- C++:字符串索引和保留标点符号时出现问题
- C++删除字符串上的标点符号,擦除()/迭代器问题