简体   繁体   English

字符串操作-混杂字符串C ++

[英]String Manipulation - Jumble Strings C++

Hello fellow programmers, I was given a homework assignment to write code that takes a string entered by the user who then chooses how to manipulate the string and in certain cases print it to the console. 程序员您好,我得到了一项家庭作业,以编写代码,该代码接受用户输入的字符串,然后用户选择如何操作该字符串,并在某些情况下将其打印到控制台。 I have the code mostly written and working but there are a couple functions I don't understand how to write. 我的代码大部分是编写的并且可以正常工作,但是有几个我不知道如何编写的函数。

One of the options is supposed to take the string and show a "jumbled version" of the string without actually changing it. 其中一个选项应该采用字符串并显示字符串的“混杂版本”,而不实际对其进行更改。 (eg. "Hello World!" becomes "oleWrl !odlH" or any other random variation each time the option is chosen.) (例如,每次选择该选项时,“ Hello World!”将变为“ oleWrl!odlH”或任何其他随机变体。)

This is the function I have now and was not accepted by my professor because it changes the original string itself. 这是我现在拥有的功能,但是我的教授没有接受它,因为它会更改原始字符串本身。

std::string jumbleString(string str2) { //jumble
  string str = str2;
  random_shuffle(str.begin(), str.end());

  return str;
}

What is an alternate way I can jumble/shuffle and print a string to get the same results? 我可以混杂/随机播放并打印字符串以获得相同结果的另一种方法是什么?

edit: Added an actual question 编辑:添加了一个实际的问题

I apologize for any formatting irregularities, this is my first time posting here. 对于任何格式不正确的问题,我深表歉意,这是我第一次在此处发布。 Thank you for any and all help. 感谢您提供的所有帮助。 :) This assignment is driving me nuts. :)这项任务使我发疯。

Well, you need to map each character to a new position... so map each original position to a new position: 好吧,您需要将每个字符映射到一个新位置...因此,将每个原始位置映射到一个新位置:

using size_type = std::string::size_type;

std::vector<size_type> pos(str2.length());
size_type n = 0;
std::generate(begin(pos), end(pos), [&]{ return n++; });
std::shuffle(begin(pos), end(pos), std::rand);
for (auto i : pos)
  std::cout << str2[i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM