C生成最大长度的随机字符串

时间:2015-11-01 17:10:53

标签: c string random ascii

我想生成一个只有小写ASCII字符的随机字符串(意思是小写字母,数字和其他ASCII字符;只是没有大写字母)。

字符串的最大长度应为587个字符(包括空终止符)。

我将如何做到这一点?

由于

3 个答案:

答案 0 :(得分:1)

#define N 588

#include <stdlib.h>
#include <time.h>
void gen(char *dst)
{
    int i, n;  

    srand(time(NULL));               /* init seed */
    if ((dst = malloc(N)) == NULL)   /* caller will need to free this */
        return;
    for (i = 0; i < N; )
        if ((n = rand()) < 'A' && n > 'Z')
            dst[i++] = n;
    dst[N - 1] = 0;                   /* null terminate the string */
}

答案 1 :(得分:1)

我试过了:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#define BUFFER_SIZE 587 /* 587 including NULL so 0..585 and 586 is NULL */

int main(int argc, char** argv)
{   
    size_t i;
    char buffer[BUFFER_SIZE];
    int x;

    srand((unsigned int)time(NULL));
    memset(buffer, 0, sizeof(buffer));

    for (i = 0; i < BUFFER_SIZE-1; i++)
    {       
        /* Note: islower returns only a b c..x y z, isdigit 0..9 and isprint only printable characters */
        do
        {
            x = rand() % 128 + 0; /* ASCII 0 to 127 */
        }
        while (!islower(x) && !isdigit(x) && !isprint(x)); 

        buffer[i] = (char)x;
    }

    buffer[BUFFER_SIZE-1] = '\0';

    printf("%s", buffer);

    getchar();

    return EXIT_SUCCESS;
}

答案 2 :(得分:0)

通过这种方式,您可以随意添加任意字符。你唯一应该把它们放在函数中

#include <stdlib.h>

void gen_random(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    s[len] = 0;
}