Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
I need to make a program that generates a random strings in C, but i don't know how to do it.
Could anyone help me?
Sorry my english bad.
Tanks.
Posted
Comments
[no name] 20-Aug-13 10:32am    
Sounds like a typical homework assignment. What have you tried and where are you stuck?

This may help you....

C#
void gen_random(char *s, const int len) {
    static const char alphanum[] =     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

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

    s[len] = 0;
}
 
Share this answer
 
v2
Comments
Salatiel Bairros 20-Aug-13 10:41am    
Tanks!
Sergey Alexandrovich Kryukov 20-Aug-13 11:51am    
It's not quite clear why do you think a "random string" could be the string composed of letters only, and static string is redundant (you should just get a random number and cast it to char), but it still shows some technique. I voted 4.
—SA
Argonia 21-Aug-13 4:01am    
Your code generates only letters. What about numbers and symbols ?
Yesudasan Moses 21-Aug-13 4:39am    
add this "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_"
I think GUID and Regex could make this much easier and reliable...

Do try the following code which creates a random different string of 20 length each time.



Guid guid = Guid.NewGuid();

           string id = guid.ToString().Substring(0, 20);
           Regex R1 = new Regex(id);
           id = Regex.Replace(id, @"\s|\-|'", "");

           Response.Write(id);



Hope that will help to.... :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900