How to get random string with spaces and mixed case?

前端 未结 3 2064
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 13:48

I am in need of generating a random string with spaces and mixedCase.

This is all I got so far:

    /// 
    /// The Typing monkey gen         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-18 14:28

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

    private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    

    Then use the RNG to access a random element in this string:

    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();
    }
    

提交回复
热议问题