创建随机字符串生成器

时间:2016-04-12 19:23:42

标签: c++ string

我试图创建一个随机字符串生成器。我用这个

创建一个从1到50的随机长度
randomLength = rand() % kMaxRandomString + kMinRandomString;

然后,我用new创建一个char指针来保存它:

char* stringBuff = new char[randomLength];

完成所有这些后,我创建了一个矢量来保存所有可能的字符。整个代码块一起看起来像这样。

void randomStringGen(char * pString)
{
  vector <string> alphaChar
  {
      R"(ABCDEFGHIJKLMNOPQRSTUVWXYZ)",
      R"(abcdefghijklmnopqrstuvwxyz)",
  };

  int randomLetterRow = 0;
  int randomLetterColm = 0;
  int randomLength = 0;
  srand(time(NULL));
  randomLength = rand() % kMaxRandomString + kMinRandomString;
  char* stringBuff = new char[randomLength];
  string test;
  for (int i = 0; i < randomLength; i++)
  {
      randomLetterRow = rand() % 2 + 1; //this chooses a row (lowercase or upper)
      randomLetterColm = rand() % 26 + 1; //this chooses a random letter from the row
      *stringBuff = alphaChar[randomLetterRow][randomLetterColm]; //I try to add the letter to the string
  }
  pString = stringBuff;
}

除了

之外,一切似乎都有效
 *stringBuff = alphaChar[randomLetterRow][randomLetterColm];

这是最重要的部分。我尝试了无数种方法。我尝试使用strcpy(),我尝试使用char数组[]。

3 个答案:

答案 0 :(得分:1)

使用std::string和C ++ 11 <random>函数,你也可以这样写:

#include <iostream>
#include <string>
#include <random>

using std::string;
using std::cout;

const string ALPHABET{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" };
std::random_device rd;

struct RandomString {

    RandomString( size_t min, size_t max, const string &alph = ALPHABET ) : 
        alphabet(alph), engine(rd()),
        random_size(min, max), random_char(0, alph.size() - 1) {}

    string operator()( size_t size = 0 ) {
        string str;
        if ( size == 0 ) {
            size = random_size(engine);
        }
        str.resize(size);
        for ( size_t i = 0; i < size; ++i ) {
            str[i] = alphabet[random_char(engine)];
        }
        return str;
    }

    private:
    const string alphabet;
    std::mt19937 engine;
    std::uniform_int_distribution<size_t> random_size,
                                          random_char;
};

int main() {

    RandomString rstr(3,10);

    for ( int i = 0; i < 5; ++i ) {
        cout << rstr() << '\n';            // random string of length 3 to 10
    }

    for ( int i = 1; i < 6; ++i ) {
        cout << rstr(i) << '\n';           // random string of length i
    }

    RandomString rhstr(4,12,"0123456789ABCDEF");  // change alphabet
    for ( int i = 0; i < 5; ++i ) {
        cout << "0x" << rhstr() << '\n';
    }

    return 0;
}

其中输出如下:

vnHlW
hscNMCTpU
ouxIwIjp
STQ
MvPyPh
t
vt
YtJ
BMWM
CmZkN
0xA047CFE
0xD95E88B
0xAB0E38CA7
0x98AE7C5A634
0xACCDA320

答案 1 :(得分:0)

问题是这句话:

 randomLetterRow = rand() % 2 + 1;

有时会产生一个2的值,这个值可能是超出范围的下标(试图得到不存在的第三行)

类似的风险:

randomLetterColm = rand() % 26 + 1;

还有一些其他项目会导致此程序无效:

  • 如果您想通过函数
  • 更改指针,则应通过引用传递指针
  • stringBuff应该有一个索引。而是stringBuff[i] =而不是*stringBuff =

所以一个完全有效的计划可能是:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>

using std::vector;
using std::string;

void randomStringGen(char*& pString)
{
    vector <string> alphaChar
    {
        R"(ABCDEFGHIJKLMNOPQRSTUVWXYZ)",
        R"(abcdefghijklmnopqrstuvwxyz)",
    };

    int randomLetterRow = 0;
    int randomLetterColm = 0;
    int randomLength = 10;
    //srand(time(NULL));
    std::srand(std::time(0));
    //randomLength = rand() % kMaxRandomString + kMinRandomString;
    char* stringBuff = new char[randomLength];
    string test;
    for (int i = 0; i < randomLength; i++) {
        randomLetterRow = rand() % 2; //this chooses a row (lowercase or upper)
        randomLetterColm = rand() % 26; //this chooses a random letter from the row
        stringBuff[i] = alphaChar[randomLetterRow][randomLetterColm]; //I try to add the letter to the string
    }
    pString = stringBuff;
}

int main()
{
    char* letters{nullptr};
    randomStringGen(letters);
    return 0;
}

如评论中所述,如果我们使用std::string作为参数,则会变得更加容易:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>

using std::vector;
using std::string;

void randomStringGen(std::string& mystring)
{
    vector <string> alphaChar
    {
        R"(ABCDEFGHIJKLMNOPQRSTUVWXYZ)",
        R"(abcdefghijklmnopqrstuvwxyz)",
    };

    int randomLetterRow = 0;
    int randomLetterColm = 0;
    int randomLength = 10;
    //srand(time(NULL));
    std::srand(std::time(0));
    //randomLength = rand() % kMaxRandomString + kMinRandomString;
    string test;
    for (int i = 0; i < randomLength; i++) {
        randomLetterRow = rand() % 2; //this chooses a row (lowercase or upper)
        randomLetterColm = rand() % 26; //this chooses a random letter from the row
        mystring.push_back(alphaChar[randomLetterRow][randomLetterColm]); //I try to add the letter to the string
    }
}

int main()
{
    std::string letters{};
    randomStringGen(letters);
    return 0;
}

答案 2 :(得分:0)

我找不到用字符串做这个的方法,所以我不得不为数组选择一个修复大小。我希望它是动态的,但这很有效。

int main(void)
{
  char pString[51] = "";
  for (int i = 0; i < 4; i++)
  {
    randomStringGen(pString);
    printf("random string: %s ",pString);
  }

return 0;
}

由于这个原因,我摆脱了向量,只是创建了一个char数组,以便更容易。

void randomStringGen(char * pString)
{
  char alphaChars[53] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  int randomLetter = 0;

  int randomLength = 0;
  srand(time(NULL));
  randomLength = rand() % kMaxRandomString + kMinRandomString;
  char stringBuff[kMaxRandomString + 1] = "";
  for (int i = 0; i < randomLength; i++)
  { 
      randomLetter = rand() % 52 + 0;
      stringBuff[i] = alphaChars[randomLetter];
  }
  strcpy(pString, stringBuff);
}