How to get a random string with spaces and mixed case?

I need random string generation with spaces and mixedCase.

This is all I got so far:

/// <summary> /// The Typing monkey generates random strings - can't be static 'cause it a monkey. /// </summary> /// <remarks> /// If you wait long enough it will eventually produce Shakespeare. /// </remarks> class TypingMonkey { /// <summary> /// The Typing Monkey Generates a random string with the given length. /// </summary> /// <param name="size">Size of the string</param> /// <returns>Random string</returns> public string TypeAway(int size) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } return builder.ToString(); } } 

I only get lowercase strings without spaces - I believe the setup should be pretty smooth to get a mixed case and spaces in the soup.

Any help is much appreciated!

+6
string c # random mixed-case
source share
3 answers

The easiest way to do this is to simply create a string with the following values:

 private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

Then use RNG to access the random item on this line:

 public string TypeAway(int size) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = legalCharacters[random.Next(0, legalCharacters.Length)]; builder.Append(ch); } return builder.ToString(); } 
+11
source share

You can start with an array of all the characters that you allow

 private static readonly char[] ALLOWED = new [] { 'a', 'b', 'c' ... '9' }; 

And then:

 { ... for (int i = 0; i < size; i++) { ch = ALLOWED[random.NextInt(0, ALLOWED.Length)]; builder.Append(ch); } ... return builder.ToString(); } return builder.ToString(); 

Paraphrase, of course. I'm not sure about the syntax of random.NextInt (), but intelisense can help.

+1
source share

You can also use Lorem Ipsum . It is widely used in the graphic design industry to fill in random realistic text without distracting the user from the design elements.

You can copy and paste a large piece of Lorem Ipsum into a constant line in your code, and then just fine-tune it to the size you need.

I found this to be better than completely random text as it is too distracting.

Hope this helps.

0
source share

All Articles