【问题标题】:Generate a string with random words生成带有随机单词的字符串
【发布时间】:2012-12-04 10:43:27
【问题描述】:

我需要编写一个函数来随机化我的字符串中的一些单词。例如:

[Hello|Hi] guys. This is my [code|string]

函数应该返回:

Hello guys. This is my code

Hi guys. This is my string

【问题讨论】:

  • 这叫做排列...
  • 你想让它有时随机说“你好”,有时说“嗨”,“代码”和“字符串”也一样?
  • 是的

标签: c# random permutation


【解决方案1】:

你可以像这样得到一个随机数生成器:

var rand = new Random();

至于解析字符串并获取所有选项,我建议您查看System.Text.RegularExpressions

到目前为止,其他答案刚刚展示了如果您已经为不同的占位符提供了一个或两个选项,您如何获得一个随机字符串。这些很好,但是写出来很无聊和乏味。最好编写一个解析器,它可以像 OP 给出的那样采用随机字符串“模板”,并使用它来生成随机字符串。

这是我整理的一个快速的:

using System;
using System.Text.RegularExpressions;

namespace StackOverLoadTest {
static class Program {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() {
        var s = new RandomString("[Hey|Hi] guys. [I|You|We|He|She] should [walk] to the [park|field|farm] sometime [today|tomorrow|next week].");
        for (int i = 0; i < 10; i++)
            Console.WriteLine(s);
    }
}

public class RandomString {
    private Random _rnd = new Random();
    private static Regex _rex = new Regex(@"\[ ( \|?  (?<option>[^]|]+) )+ \]", System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.ExplicitCapture);
    string _template;
    public RandomString(string template) {
        _template = template;
    }
    public override string ToString() {
        return _rex.Replace(_template, GetRandomOption);
    }
    public string GetRandomOption(Match m) {
        var options = m.Groups["option"].Captures;
        int choice = _rnd.Next(0, options.Count);
        return options[choice].Value;
    }
}
}

如您所见,您使用模板创建一个新的 RandomString 对象。然后只需调用 ToString() 函数任意次数,每次都得到一个新的随机排列选项。

您可以使用任意数量的占位符和任意数量的选项(0 除外)。 我在这个例子中使用的字符串模板是:

"[Hey|Hi] guys. [I|You|We|He|She] should [walk] to the [park|field|farm] sometime [today|tomorrow|next week]."

运行上面的代码,得到如下结果:


Hey guys. I should walk to the park sometime today.
Hi guys. We should walk to the farm sometime today.
Hi guys. He should walk to the field sometime next week.
Hey guys. You should walk to the park sometime next week.
Hi guys. She should walk to the farm sometime next week.
Hey guys. We should walk to the field sometime tomorrow.
Hi guys. I should walk to the farm sometime today.
Hey guys. He should walk to the field sometime tomorrow.
Hi guys. You should walk to the park sometime next week.
Hi guys. I should walk to the farm sometime today.

【讨论】:

  • 最佳和最可插入的答案。
  • 哦,嘿,Replace 很好用。比我想要的要简单得多。
  • 谢谢。实际上,您可能可以在正则表达式上多做一些工作。这不是我想要的,但它允许在单个匹配中多次捕获“选项”。这就是使正则表达式能够为每个占位符使用无限数量的选项而不是只有两个(或任何其他固定数量)的能力。
【解决方案2】:

试试这个:

private string randArr(String[] _arr)
{
    Random _rnd = new Random(DateTime.Now.GetHashCode());
    return _arr[_rnd.Next(_arr.length)];
}

只需调用它为您的数组提供字符串值。像这样:

String.Format("{0} guys. This is my {1}", randArr(["Hello","Hi"]), randArr(["code","string"]));

【讨论】:

    【解决方案3】:

    我使用了这种方法:

    Random rand = new Random();
    int val = rand.Next(0, 100);
    Console.WriteLine(
        "{0} guys. This is my {1}",
    
        val >= 50 ? "Hi" : "Hello",
        val < 50 ? "code" : "string");
    

    我给了一个 50%-50% 的机会来写什么词,所以这就是你看到的 &gt;= 50&lt; 50你可以改变它。

    如果你想随机化每个单词,而不是完整的句子(上面的代码只给你 2 个变体),只需弄乱代码或评论我来修改它。

    注意事项:

    实际上不是 50%-50%。我不想混淆,但如果你想要这样,第一个条件应该是&gt;= 49*

    条件 (condition ? statement : statement) 的语法称为 ternary if operator

    【讨论】:

    • 如果 val 正好是 50 会发生什么?
    • @FlorisPrijt 是的,我会立即对其进行编辑!谢谢你指出。
    • 这绑定了两个结果。您将始终拥有 Hello + 字符串或 Hi + 代码。其他组合将永远不会显示,因为您对两者使用相同的随机值。
    • @Flater 正如我在第二段中所说的那样。我不确定,所以我把它留给了 OP 来评论我。你确定这就是他想要的吗?
    • 无论哪种方式,您的选项都会显示原始问题中未提及的两个结果,使用此 sn-p 无法接收特别要求的两个输出。不过没有冒犯,总的来说,它是可靠的编程:)
    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 2018-04-14
    • 2017-08-01
    • 2011-06-30
    • 2015-04-05
    • 2013-10-01
    相关资源
    最近更新 更多