如何创建一个随机混乱字符串的函数

0 c++ string pointers char

我的main函数包含一个我想混杂的字符串.我找到了一段传入a的代码,char*完成后返回0.我已经按照代码提供程序的说明简单地传入了你想要混乱的字符串.

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

int scrambleString(char* str)
{
     int x = strlen(str);
     srand(time(NULL));
     for(int y = x; y >=0; y--)
     {
          swap(str[rand()%x],str[y-1]);
     }
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我收到一个错误"no suitable conversion function "std::string" to "char*" exists.

我也试过传入const char*但是不允许我访问这个词并改变它.

Ben*_*ley 7

试试这个:

std::string s = "Hello";
std::random_shuffle(s.begin(),s.end());
Run Code Online (Sandbox Code Playgroud)

对了,不要忘记,包括<algorithm>为了使用std::random_shuffle,而你需要包括<string>std::string.<string.h>是用于c-string库,如果你打算在C++中使用它,你应该实际使用它<cstring>.