字符串中存储的字符 - 随机化时如何将它们存储在另一个字符串变量中

时间:2016-10-13 21:17:48

标签: c string random generator

美好的一天!我是一名新手程序员,我仍然对如何应用C的概念感到困惑。

我正在开展一个项目。我的问题是我已经初始化了某些字符并将它们存储在一个字符串中(vars [28])。我的目标是以随机方式生成字符串的字符,并将生成的字符串存储在另一个变量中,我不知道如何。

int randnum = 0, num = 0;
char vars[28] = "|abcdefghijklmonpqrstuvwxyz."; //initialized string
char term; //where to store randomized string
int i = 0;
char choi[1];

printf ("%c", vars[0]);

srand (time(NULL));
randnum = rand() % 30; //only 30 characters maximum to be stored        

for (i = 0; i <= randnum; i++)
{
    //randomly produce vars[28] characters here and store into 'term'
}

其他问题:我如何防止|和。随机时彼此相邻?

谢谢!

1 个答案:

答案 0 :(得分:2)

term只是单个字符。字符串是数组的字符。标准C字符串以0结尾。因此,为了创建随机字符串,您的程序应如下所示:

int randnum = 0;
char* vars = "|abcdefghijklmonpqrstuvwxyz."; // array of alowed characters
char term[30 + 1]; // allocating an array of 30 characters + 1 to hold null terminator
int i = 0;

srand (time(NULL));
int length = rand() % 30 + 1; // random length up to 30, minimum 1 character (the +1)

for (i = 0; i < length; i++)
{
    randnum = rand() % 28; // random index to the array of allowed characters
    term[i] = vars[randnum]; // assign random character to i-th position of term
}
term[i] = '\0'; // end string

printf("%s\n", term);

我强烈建议你跟进关于C语言的讲座 - 第一章(上),应该清除一切!