【问题标题】:Find lines that contains a specific string and randomly pick one in c#查找包含特定字符串的行并在 c# 中随机选择一个
【发布时间】:2016-01-11 08:43:25
【问题描述】:

所以,我有一个如下所示的文本文件:

[hello]Hi
[hello]welcome back 
[hello]Hello sir 
[goodbye]goodbye sir
[goodbye]until next time
...

下面是部分代码:

string[] responseLines = File.ReadAllLines(@"responses.txt");
Random rand = new Random();
string response;

case "hello":
    chatBox.Items.Add(Me);
    response = responseLines[rand.Next(responseLines.Length)];
    JARVIS.SpeakAsync(response);
    chatBox.Items.Add("Jarvis: " + response);
    break;

问题是我只想找到包含[hello] 的行,然后随机选择其中之一。

【问题讨论】:

    标签: c# string text random io


    【解决方案1】:

    读取文件中的所有字符串后,将它们拆分为两个不同的列表:

    string[] responseLines = System.IO.File.ReadAllLines(@"responses.txt");
    List<string> helloStrings = responseLines.Where<string>(str => str.StartsWith("[hello]")).Select(str => str.Replace("[hello]", "")).ToList<string>();
    List<string> goodByeStrings = responseLines.Where<string>(str => str.StartsWith("[goodbye]")).Select(str => str.Replace("[goodbye]", "")).ToList<string>();
    

    现在从您需要的列表中选择一个随机元素

    【讨论】:

    • 也可以!正是我想要的:)
    • 我试过但我不能?我是这个网站的新手。我认为我需要至少 15 点声望?
    • 也许,我也是这个网站的新手。我赞成您的评论,我认为这给了您一些声誉点。无论如何,并不重要。
    【解决方案2】:

    代替

    string[] responseLines = File.ReadAllLines(@"responses.txt");
    

    使用

    string[] responseLines = File.ReadAllLines(@"responses.txt").Where(s => s.Contains("[hello]")).ToArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 2012-10-19
      • 2021-12-13
      • 1970-01-01
      • 2018-04-22
      • 2020-11-01
      相关资源
      最近更新 更多