0

hey everyone, im tryin to generate random strings and store them in an array. can anyone please show me?

5
Contributors
6
Replies
8
Views
6 Years
Discussion Span
Last Post by Narue
0

Generating random strings as a whole is tough ...
You could chose a random length and then chose random chars to fill that length

0

yes, i know i need a length.
for example:

my_string="abcdefghijklmnopqrstuvwxz"; //these are my random chars
char list[10]; //the array where i want to store the randomly generated chars

now how can i do that.
i only know how to generate random integers

0

Look at ASCII table and note the decimal values of chars you want to randomize. Then randomize values, then print them with using "%c" placeholder. For example;

char example = 97;
int exapmleinteger = 97;
printf("%c", example );
printf("%c", exampleinteger );

will both output 'a'.

http://www.asciitable.com/

0

darkdai> my_string="abcdefghijklmnopqrstuvwxz"; //these are my random chars
Doesn't look very random. In fact, it has the same pattern that ABC's, except missing the 'y'

yes, i know i need a length.
for example:

my_string="abcdefghijklmnopqrstuvwxz"; //these are my random chars
char list[10]; //the array where i want to store the randomly generated chars

now how can i do that.
i only know how to generate random integers

strcpy() could be the function you need to save the string. As long as list[] has enough space to save the given string. That's twenty-five chars + a null terminator, in your post. Thus

my_string="abcdefghijklmnopqrstuvwxz";
char list[26];
strcpy(list, my_string);

Here's an example of generating some noise.
Another example if you need more.

Edited by Aia: n/a

0

the letters arent the random chars. they are the letters that i want to generate random chars from

0

im tryin to generate random strings and store them in an array. can anyone please show me?

It's easy if you really want random (pseudorandom) strings from a source:

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

void random_fill(char s[], size_t n, const char *src)
{
    size_t src_len = strlen(src);
    size_t i;

    for (i = 0; i < n; i++)
    {
        s[i] = src[rand() % src_len];
    }
}

int main(void)
{
    const char *src = "abcdefghijklmnopqrstuvwxyz";
    const size_t n = 10;
    char s[10] = {0};

    srand((unsigned)time(NULL));
    random_fill(s, n - 1, src);
    puts(s);

    return 0;
}

Where it really gets interesting is if you don't want duplicate characters in the string.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.