gpt4 book ai didi

c++ - 如何创建一个随机打乱字符串的函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:48 38 4
gpt4 key购买 nike

我的主函数包含一个我想打乱的字符串。我找到了一段代码,它传入 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;
}

当我这样做时,我收到一个错误,提示 “不存在从“std::string”到“char*”的合适的转换函数

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

最佳答案

试试这个:

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

顺便说一下,不要忘记包含 <algorithm>为了使用 std::random_shuffle , 你需要包括 <string>对于 std::string . <string.h>用于 c 字符串库,如果你打算在 C++ 中使用它,你实际上应该使用 <cstring>相反。

关于c++ - 如何创建一个随机打乱字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5037073/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com