C#用随机生成的字符串

时间:2018-05-30 21:21:36

标签: c# random replace

你好StackOverFlow的人,我写了下面的错误代码有问题。我的问题是如何用随机生成的字符串替换下面的每个单词。

我的问题是下面的代码,现在它正在随机替换所有单词,但它们都是相同的,我想要的是用随机生成的字符串替换每个单词而不是全部相同...

我在资源中多次使用过这些字符串。

我在资源中的说法是:“basenet”,“R02”,“R01”,“R03”,“R0”,“vistubularcut”,“naturalipad”,“braskausa”,“moonsteelir”,“dubilomo” “

我的代码:

public string RandomGen1(int a1, Random random) {
  StringBuilder result1 = new StringBuilder(a1);
  string characters = textBox1.Text;
  for (int i = 0; i < numericUpDown1.Value; i++) {
    result1.Append(characters[random.Next(characters.Length)]);
  }
  return result1.ToString();
}

private void button1_Click(object sender, EventArgs e) {
    Random rnd = new Random();
    string[] gen1 = new string[1];
    for (int a = 0; a < gen1.Length; a++) {
      gen1[a] = RandomGen1(1, rnd);
      string source = (String.Join(Environment.NewLine, gen1));
      string executionerv2 = Properties.Resources.String1;

      string[] replace1 = {
        "basenet",
        "R02",
        "R01",
        "R03",
        "R0",
        "vistubularcut",
        "naturalipad",
        "braskausa",
        "moonsteelir",
        "dubilomo"
      };

      foreach (string curr in replace1) {
        executionerv2 = executionerv2.Replace(curr, source);
      }
    }

2 个答案:

答案 0 :(得分:2)

您可以使用Random生成随机数,将其转换为char并附加到string

private string RandomString(int length)
    {
        Random rdn = new Random();
        string toReturn = string.Empty;
        while (length > 0)
        {
            toReturn += (char)rdn.Next(65, 90);
            length--;
        }

        return toReturn;
    }

我选择了基于ASCII表的范围:https://www.asciitable.com/ 如果您还想要随机length,只需在调用方法中创建Random的新实例。

修改

根据评论,这是一种更好的方法。

private string RandomString(int length)
    {
        Random rdn = new Random();
        return new string((char)rdn.Next('A', 'Z'), length);
    }

最后你可以简单地写一下:replace1[index] = RandomString(4);

答案 1 :(得分:0)

String.Replace(string, string)将使用第二个参数字替换第一个参数字的每个实例。如果您希望将同一个单词的每个单独实例替换为不同的字符串,则必须将字符串的单词分开,迭代它们,每次找到要替换的单词时,请用随机字符串替换它。 / p>

这是一个例子(假设你已经有了获取随机词的方法):

string Source = "The quick brown fox jumps over the lazy dog.\r\nThe quick brown fox jumps over the lazy dog.";
string[] ReplaceWords = { "quick", "fox", "lazy", "dog" };

string[] SourceWords = Source.Split(' ');
string result = "";
for (int i = 0; i < SourceWords.Length; i++)
{
    if (ReplaceWords.Contains(SourceWords[i]))
        result += " " + GetRandomWord();
    else
        result += " " + SourceWords[i];
}
result = result.Trim() //Remove white spaces at the begining and end of the string.

result = "The fdhs brown fdsfsd jumps over the hgfih turioutro.\r\nThe cxnvcxn brown oipuop jumps over the rewrre kmlçnlç."

这样,单词“quick”,“fox”,“lazy”和“dog”的每个实例都将被不同的字符串替换。在我的例子中,我显然只是随机地敲击键盘以说明我的观点,但如果你有一个GetRandomWord函数从列表中获取现有单词,它也会起作用:

result = "The tree brown house jumps over the grass shell.\r\nThe hidrant brown mushroom jumps over the ocean skateboard."

我的例子都是迟钝的,但它们说明了我的观点。

我希望我帮助过。)

只是为了好玩

如果你创建一个GetRandomWord来选择现有列表中的单词并且它具有上下文感知功能,那么你可以获得可能实际上有意义的句子。

让我们为我们的上下文创建一个enum。为了简单起见......让我们保持简单:

enum Context
{
    Adjective,
    Noun
}

现在让我们创建我们的列表:

string[] Nouns = {"dog", "cat", "fox", "horse", "bird"};
string[] Adjectives {"lazy", "sleepy", "quick", "big", "small"};

现在我们的方法:

string GetRandomWord(Context c)
{
    Random R = new Random();
    switch (c)
    {
        case Context.Noun:
            return Nouns[R.Next(0, Nouns.Length)];
            break;
        case Context.Adjective:
            return Adjectives[R.Next(0, Adjectives.Length)];
            break;
    }
}

现在对文本替换代码稍作修改:

string Source = "The quick brown fox jumps over the lazy dog.\r\nThe quick brown fox jumps over the lazy dog.";
string[] ReplaceAdjectives = { "quick", "lazy" };
string[] ReplaceNouns = { "fox", "dog" };

string[] SourceWords = Source.Split(' ');
string result = "";
for (int i = 0; i < SourceWords.Length; i++)
{
    if (ReplaceAdjectives.Contains(SourceWords[i]))
        result += " " + GetRandomWord(Context.Adjective);
    else if (ReplaceNouns.Contains(SourceWords[i]))
        result += " " + GetRandomWord(Context.Noun);
    else
        result += " " + SourceWords[i];
}
result = result.Trim() //Remove white spaces at the begining and end of the string.

result = "The sleepy brown bird jumps over the small horse.\r\nThe lazy brown cat jumps over the sleepy dog."

像我说的那样,这样的结果随机句可能会有所帮助。但至少从语法的角度来看,它会有所帮助。

因为我们的列表与名词的标记与其相应的感觉形容词形容词相匹配,我们也可以修改代码,以便我们得到保证有意义的随机结果。

我们所要做的就是创建一个名为GetMatchingWord(Context, int)的新方法。它需要一个int,因为它不再将单词选择随机化。这现在在调用方法中完成。

string GetMatchingWord(Context c, int i)
{
    switch (c)
    {
        case Context.Noun:
            return Nouns[i];
            break;
        case Context.Adjective:
            return Adjectives[i];
            break;
    }
}

然后我们相应地修改我们的代码:

string Source = "The quick brown fox jumps over the lazy dog.\r\nThe quick brown fox jumps over the lazy dog.";
string[] ReplaceAdjectives = { "quick", "lazy" };
string[] ReplaceNouns = { "fox", "dog" };

bool GuaranteeMatch = true;

string[] SourceWords = Source.Split(' ');
string result = "";
Random R = new Random();
for (int i = 0; i < SourceWords.Length; i++)
{
    if (GuaranteeMatch)
    {
        int I = R.Next(0, Adjectives.Length) //Adjectives and Nouns have the same Length. This is a requirement for this method to work.
        if (ReplaceAdjectives.Contains(SourceWords[i]))
            result += " " + GetMatchingWord(Context.Adjective, I);
        else if (ReplaceNouns.Contains(SourceWords[i]))
            result += " " + GetMatchingWord(Context.Noun, I);
        else
            result += " " + SourceWords[i];
    }
    else
    {
        if (ReplaceAdjectives.Contains(SourceWords[i]))
            result += " " + GetRandomWord(Context.Adjective);
        else if (ReplaceNouns.Contains(SourceWords[i]))
            result += " " + GetRandomWord(Context.Noun);
        else
            result += " " + SourceWords[i];
    }
}
result = result.Trim() //Remove white spaces at the begining and end of the string.

现在,如果GuaranteeMatch为真,我们将始终获得如下结果: result = "The big brown horse jumps over the sleepy cat.\r\nThe lazy brown dog jumps over the small bird."

它甚至可以返回原始句子,因为被替换的单词也存在于单词列表中以替换它们。