开发者

How to create a function which randomly jumbles a string

开发者 https://www.devze.com 2023-02-12 07:02 出处:网络
My main function contains a string that I would like to jumble. I have found a piece of code which passes in a char* and returns 0 when complete. I have followed the code providers instructions to sim

My main function contains a string that I would like to jumble. I have found a piece of code which passes in a char* and returns 0 when complete. I have followed the code providers instructions to simply pass in the string which you would like to have jumbled.

#include <iostream>
#include <string.h>
#include <time.h>
using namespace std;

int scrambleString(char* str)
{
     int x = strl开发者_如何转开发en(str);
     srand(time(NULL));
     for(int y = x; y >=0; y--)
     {
          swap(str[rand()%x],str[y-1]);
     }
     return 0;
}

When I do this, I recieve an error that "no suitable conversion function "std::string" to "char*" exists.

I have also tried passing in a const char* but that won't allow me to access the word and change it.


Try this instead:

std::string s = "Hello";
std::random_shuffle(s.begin(),s.end());

By the way, don't forget to include <algorithm> in order to use std::random_shuffle, and you need to include <string> for std::string. <string.h> is for the c-string library, and if you're going to use that in C++, you should actually use <cstring> instead.


Why are you mixing std::string with char*? You should just operate directly on the string:

void scrambleString(std::string& str) 
{
    int x = str.length();
    for(int y = x; y > 0; y--) 
    { 
        int pos = rand()%x;
        char tmp = str[y-1];
        str[y-1] = str[pos];
        str[pos] = tmp;
    }
}

Usage becomes:

    std::string value = "This is a test";
    scrambleString(value);

That being said, std::random_shuffle will do this for you...


std::string class cannot be converted to char* implicitly. You have to use string.c_str() to convert to const char* from std::string.

Notice c_str() returns a const pointer to the string copied from std::string internal storage so you cannot change its content. instead, you have to copy to another array or vector.


Try using it like this:

std::string stringToScramble = "hello world";

scramble(stringToScramble.c_str());

Notice the use of .c_str() which should convert the string into the format that you need.


If you want to write random char data into a string, the C++ way using random library is:

#include <random>

std::string mystring = "scramble this please";

std::default_random_engine rng;
std::uniform_int_distribution<int> rng_dist(0, 255);
for(unsigned int n = 0; n != mystring.size(); ++n) {
  mystring[n] = static_cast<unsigned char>(rng_dist(rng));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号