Randomizing a string [duplicate]

2019-03-07 02:22发布

This question already has an answer here:

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.

标签: c# string random
2条回答
何必那么认真
2楼-- · 2019-03-07 02:40
Random rand = new Random();
var output = new string(input.OrderBy(x => rand.Next()).ToArray());
查看更多
成全新的幸福
3楼-- · 2019-03-07 02:45

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()));
查看更多
登录 后发表回答