如何扰乱字符串C#?

时间:2012-11-12 04:54:32

标签: c# .net

我写代码来争夺单词我创造简单的游戏混乱

         string jumble = theWord;
         int length = jumble.Count();
         for (int i = 0; i < length; ++i)
         {
             int index1 = (rand.Next() % length);
             int index2 = (rand.Next() % length);

             char  temp =jumble[index1];
             jumble = jumble.Replace(jumble[index1], jumble[index2]);
             jumble = jumble.Replace(jumble[index1], temp);

         }

更新代码

         string jumble = theWord;
         int length = jumble.Count();
         for (int i = 0; i < length; ++i)
         {
             int index1 = (rand.Next() % length);
             //int index2 = (rand.Next() % length);

         char temp = jumble[index1];
         jumble[i] = jumble[index1 - 1];
         jumble[i] = temp;

         }
  

错误1无法将属性或索引器'string.this [int]'分配给    - 它是只读的

3 个答案:

答案 0 :(得分:4)

         StringBuilder jumbleSB = new StringBuilder();
         jumbleSB.Append(theWord);
         int lengthSB = jumbleSB.Length;
         for (int i = 0; i < lengthSB; ++i)
         {
             int index1 = (rand.Next() % lengthSB);
             int index2 = (rand.Next() % lengthSB);

             Char temp = jumbleSB[index1];
             jumbleSB[index1] = jumbleSB[index2];
             jumbleSB[index2] = temp;

         }

         Console.WriteLine(jumbleSB);
    }

答案 1 :(得分:3)

为了清晰和排列的良好分布(可能考虑到性能),我会选择这个:

public static class Ext
{
    private static Random rand = new Random();

    public static string Shuffle(this String str)
    {
        var list = new SortedList<int,char>();
        foreach (var c in str)
            list.Add(rand.Next(), c);
        return new string(list.Values.ToArray());
    }
}
  • 注意其他答案:一个是严重偏见,另一个不会给所有可能的洗牌。如果你不关心这类东西,这些都是有效的答案。

答案 2 :(得分:2)

var jumble = new StringBuilder("theWord");
int length = jumble.Length;
var random = new Random();
for(int i=length-1; i>0; i--)
{
    int j = random.Next(i);
    char temp = jumble[j];
    jumble[j] = jumble[i];
    jumble[i] = temp;
}
Console.WriteLine(jumble);