Max Orozco Max Orozco - 1 year ago 170
C++ Question

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.)

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.

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download