C# 在另一个字符串的字符之间插入一个随机字符串
C# Insert a random string in between characters in another string
我想制作一种方法,在字符串中的字符之间插入随机的十六进制颜色。这是我到目前为止所拥有的。
`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}", "[=10=]" + hexcolor);
return ouput;
}`
这使得字符串 "input"
看起来像 [FF0000]I[FF0000]n[FF0000]p[FF0000]u[FF0000]t"
。如何每次都使十六进制代码成为新的随机数?
您应该将 Random
实例移到该函数之外(进入您的 class 成员)您也可以从调用函数传入它。
问题是,如果您在紧密循环中调用该方法(您可能是这样),那么每次都会使用相同的种子创建它。由于它具有相同的种子,因此生成的第一个数字对于所有调用都是相同的,显示您的行为。
正确的代码是:
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}", "[=10=]" + hexcolor);
return ouput;
}
我想制作一种方法,在字符串中的字符之间插入随机的十六进制颜色。这是我到目前为止所拥有的。
`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}", "[=10=]" + hexcolor);
return ouput;
}`
这使得字符串 "input"
看起来像 [FF0000]I[FF0000]n[FF0000]p[FF0000]u[FF0000]t"
。如何每次都使十六进制代码成为新的随机数?
您应该将 Random
实例移到该函数之外(进入您的 class 成员)您也可以从调用函数传入它。
问题是,如果您在紧密循环中调用该方法(您可能是这样),那么每次都会使用相同的种子创建它。由于它具有相同的种子,因此生成的第一个数字对于所有调用都是相同的,显示您的行为。
正确的代码是:
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}", "[=10=]" + hexcolor);
return ouput;
}