当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - C# Insert a random string in between characters in another string

问题描述:

I want to make a method that inserts a randomized hex color in between characters in a string. This is what I have so far.

`public static string colorString(string input)

{

var random = new System.Random();

string hexcolor = "[" + String.Format("{0:X6}", random.Next(0x1000000)) + "];

string output = Regex.Replace(input, ".{0}", "$0" + hexcolor);

return ouput;

}`

this makes like a string "input" look like [FF0000]I[FF0000]n[FF0000]p[FF0000]u[FF0000]t". How do I make the hexcode a new random every time?

网友答案:

You should move the Random instantiation outside that function (into your class members) You could also just pass it in from the calling function.

The problem is that if you are calling that method in a tight loop (which you likely are), then it will be created with the same seed each time. Since it has the same seed, the first number generated will be the same for all invocations, showing your behavior.

The correct code would be:

Random random = new System.Random();

public static string colorString(string input)
{   
    string hexcolor = "[" + String.Format("{0:X6}", random.Next(0x1000000)) + "];
    string output = Regex.Replace(input, ".{0}", "$0" + hexcolor);
    return ouput;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: