将随机数/字母代码转换为有序读取?

时间:2013-05-06 13:01:32

标签: c# string winforms int

所以这是一个noobish问题,但我有这个代码,它会生成随机数字和字母。

使用此代码:

private readonly Random _rng = new Random();
private const string charaters = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";

    private string RandomString(int size)
    {
        char[] buffer = new char[size];

        for (int i = 0; i < size; i++)
        {
            buffer[i] = charaters[_rng.Next(charaters.Length)];
        }
        return new string(buffer);
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
         textBox3.Text = RandomString(5);
    }    

我希望它能够通过随机读取所有字符。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

我不确定你的意思,但这会返回“AaBbC”:

characters.Substring(0,5);

将您的评论拼凑在一起,我认为您正在寻找的是:

string s = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
foreach (char c in s)
{
    textBox3.Text += c.ToString() + Environment.Newline; // or perhaps textBox2?
}

答案 1 :(得分:2)

这会起作用吗?

class Program
{
    private static readonly Timer Timer = new Timer(100); 
    public static int CurrentValue;
    private const string Charaters = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";

    static void Main()
    {
        Timer.Elapsed += delegate
                              {
                                  if (CurrentValue < Charaters.Length)
                                  {
                                      Console.Write(string.Format("{0}{1}", Charaters[CurrentValue], Environment.NewLine));
                                      CurrentValue++;
                                  }
                                  else
                                  {
                                      Timer.Stop();
                                  }
                              };
        Timer.Enabled = true;
        Console.ReadLine();
    }

答案 2 :(得分:1)

使用LINQ的简单解决方案:

string test = RandomString(5);
string result = string.Join(string.Empty, test.OrderBy(z => z));

这是有效的,因为stringchar的数组。