How to get random string with spaces and mixed case?

我怕爱的太早我们不能终老 提交于 2019-12-01 18:11:45

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

You could start with an array of all the characters you'll 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();

I paraphrase, of course. I'm not certain about the syntax on random.NextInt(), but intelisense aught to help.

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

You can copy and paste a big chunk of the Lorem Ipsum into a constant string in your code and then just substring it into whatever sizes you need.

I found this was better than having completely random text since it was too distracting.

Hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!