我需要生成一个包含空格和mixedCase的随机字符串.
到目前为止我已经完成了This:
/// <summary> /// The Typing monkey generates random strings - can't be static 'cause it's 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(); } }
我只得到没有空格的大写字符串 – 我相信调整应该非常严格,以便在汤中混合大小写和空格.
任何帮助非常感谢!
解决方法
最简单的方法是简单地创建一个包含以下值的字符串:
private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
然后使用RNG访问此字符串中的随机元素:
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(); }