gpt4 book ai didi

c# - 如何获得带有空格和混合大小写的随机字符串?

转载 作者:太空狗 更新时间:2023-10-29 21:07:37 26 4
gpt4 key购买 nike

我需要生成一个包含空格和大小写混合的随机字符串。

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

关于c# - 如何获得带有空格和混合大小写的随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com