【问题标题】:C# Insert a random string in between characters in another stringC# 在另一个字符串的字符之间插入一个随机字符串
【发布时间】:2015-04-04 08:55:13
【问题描述】:

我想创建一种在字符串中的字符之间插入随机十六进制颜色的方法。这就是我到目前为止所拥有的。

`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;
}`

这使得字符串"input" 看起来像[FF0000]I[FF0000]n[FF0000]p[FF0000]u[FF0000]t"。如何每次都使十六进制代码成为一个新的随机数?

【问题讨论】:

  • 使用相同的Random 对象。

标签: c# .net random replace colors


【解决方案1】:

您应该将 Random 实例移到该函数之外(到您的类成员中)您也可以只从调用函数中传递它。

问题在于,如果您在紧密循环中调用该方法(您可能是这样),那么每次都会使用相同的种子创建它。由于它具有相同的种子,因此生成的第一个数字对于所有调用都将相同,从而显示您的行为。

正确的代码是:

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;
}

【讨论】:

    猜你喜欢
    • 2016-02-07
    • 2022-01-08
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2012-09-25
    相关资源
    最近更新 更多