Randomizing a string [duplicate]

2019-03-07 01:44发布

问题:

This question already has an answer here:

  • Best way to randomize an array with .NET 18 answers

I'm new to C# so don't blame me for my stupidity. I'm working on an application that should randomize a word and give it's lenght for example you write a word "Line" and it gives you "iLen". Currently I'm sure that only this part works:

    private void lenght_Click(object sender, EventArgs e)
    {
        String word = textBox1.Text;
        int x = word.Length;
        MessageBox.Show(x.ToString());
    }

    private void randomize_Click(object sender, EventArgs e)
    {
        String word = textBox1.Text;
        int x = word.Length;


    }

I tried a lot but most of it just crashed the application so at the moment I would like to know what does the Text.ToCharArray does and I would love additional support. So I just need a method that takes your string randomizes it gives you another string just with mashed/randomized characters. Now I will leave the question for 5 - 7 hours to get more answers later I will review them all and give rep to the working ones. Thank you for support! I have read all your reviews yet I'm late sorry for that now it's time to check everything.

回答1:

Randomize method (from another SO question):

public static T[] Randomize<T>(T[] source)
{
    List<T> randomized = new List<T>();
    List<T> original = new List<T>(source);
    Random r = new Random();
    for (int size = original.Count; size > 0; size--)
    {
        int index = r.Next(size);
        randomized.Add(original[index]);
        original[index] = original[size - 1];
    }
    return randomized.ToArray();
}

And usage:

string text = "Line";

string randomized = new string(Randomize(text.ToCharArray()));


回答2:

Random rand = new Random();
var output = new string(input.OrderBy(x => rand.Next()).ToArray());


标签: c# string random