【问题标题】:using LINQ to separate a list element and inserting the results back to list使用 LINQ 分隔列表元素并将结果插入到列表中
【发布时间】:2014-08-15 14:27:54
【问题描述】:

我有一个这样的字符串列表(""Joe", "wants", "to", "谢谢", "you!"") 我想要的是分开 "you", "!"和 """ 并使用 LINQ 将它们插入回该列表。我知道这里有很多 LINQ 专家,可以在一分钟内完成。我正在做的是将一个句子分成单词:

    string sentence = "\"Joe wants to thank you!\"";
    string[] words = sentence.split(" ");
    List<string> result = new List<string>();

    for (int i = 0; i < words.Length; i++)
    {
        string word = words[i];
        if (word.EndsWith("."))
        {
            result.Add(word.Substring(0, word.LastIndexOf(".")));
            result.Add(".");
        }
        else if (word.EndsWith("..."))
        {
            result.Add(word.Substring(0, word.LastIndexOf("...")));
            result.Add("...");
        }
        else if (word.EndsWith(","))
        {
            result.Add(word.Substring(0, word.LastIndexOf(",")));
            result.Add(",");
        }
        else if (word.EndsWith("\""))
        {
            result.Add(word.Substring(0, word.LastIndexOf("\"")));
            result.Add("\"");
        }


     }

问题在于句子以 !" 结尾。注意:words 是由空格分隔的数组。

【问题讨论】:

  • 这些字符串有什么模式吗?似乎定期删除可以完成工作。
  • @liran63 ??如何将一个单独的单词删除后跟一个标点符号,将其放回列表中?
  • 在您的代码中,(""", "Joe", "wants", "to", "thank", "you!", """) 是否只是 "Joe wants to thank you!"
  • 我猜他正在寻找的只是添加另一个 else if (word.EndsWith("!")) ... ;还是我错过了什么?
  • 你可以先string.replace("!", " !"),然后再用空格分割

标签: c# asp.net linq list word


【解决方案1】:

也许您只是在寻找正则表达式?

var sentence = "\"Joe wants to thank you!\"";
var result = Regex.Split(sentence, @"(\.{3}|\W)").Where(w => !String.IsNullOrWhiteSpace(w));

现在的结果是:

【讨论】:

  • 这不处理省略号的情况(显示在问题的示例代码中)。它将三个连续的时段分成三个休息时间。
  • @YaakovEllis 谢谢。没注意这个。修好了。
【解决方案2】:

因为你已经用空格分割了,所以只需 replace 并在分割之前添加一个空格

sentence = sentence.Replace("!", " !");

我认为你不需要 linq,但对你来说有点优雅

var addMyspace = new List<string>{"!", "...", "\"", ".", ","};

foreach(var s in addMyspace)
{
     sentence = sentence.Replace(s, string.Format(" {0}",s));
}
//split

【讨论】:

    【解决方案3】:

    这是一个解决方案,它更注重使用Regex.Split 而不是使用 Linq(尽管仍然使用 Linq):

    string sentence = "\"Joe wants to thank you! comma, ellipsis...exclamation! period.\""; 
    string pattern = @"(\.\.\.)|([ ""\.,\\!])";
    IEnumerable<string> words = Regex.Split(sentence, pattern)
                                     .Where (x => !String.IsNullOrWhiteSpace(x));
    foreach (var word in words) { Console.WriteLine(word); }
    

    正则表达式本身会拆分您想要拆分的任何字符,包括省略号(请注意它首先出现在正则表达式中的方式)。正则表达式使用捕获在输出中返回拆分字符,然后使用 Linq 去除空项和单个空格。

    这个的输出是:

    "
    Joe
    wants
    to
    thank
    you
    !
    comma
    ,
    ellipsis
    ...
    exclamation
    !
    period
    .
    "
    

    【讨论】:

    • 非常好,但是这种形式的句子怎么样: string sentence = "\"Joe 要感谢你!\" 这是另一个句子,我们将......让它工作!对现在。”;
    • @Gohomeurdrunk 我将其修改为也拆分引号。
    • 谢谢 Yaakov,您的代码很好,但我可以接受 1 个答案,而且我对正则表达式不太熟悉,无法按我的意愿修改它。但赞成它
    【解决方案4】:

    如果输入数组曾经是一个普通字符串,则使用正则表达式将其拆分为\b 会更简单,这意味着"word boundary"

    var splitted = Regex.Split(input_string, @"(\.\.\.)|(\W)")
            .Where(chunk => !string.IsNullOrWhiteSpace(chunk))
            .Select(chunk => chunk.Trim());
    

    同样适用于空格和标点符号,但将数字视为单词的一部分(例如,Joe2 在拆分后仍将保留Joe2)。

    另外,由于\b 是零长度匹配,空格被视为“单词”,因此使用Where 删除它们。

    详情请参阅Regex.SplitWhere

    编辑:在修复了线程中其他人指出的缺陷后,这个答案与他们的基本相同。看起来这个问题的所有正确答案都是相同的,但每个错误答案都是唯一错误的:)

    【讨论】:

    • 按字边界分割不会将!"分割成!"
    【解决方案5】:

    这是一个适用于您在字符串中可能遇到的任何类型的标点符号的解决方案。

    Regex regex = new Regex(@"(\w+|(\W)\2*)");
    
    string sentence = "\"Joe wants to thank you! Here is another sentence, where we will...get this to work! Right now.\"";
    
    var words = regex.Matches(sentence).Cast<Match>().Where(m => !String.IsNullOrWhiteSpace(m.Value)).Select(m => m.Value);
    
    foreach (var word in words)
        Console.WriteLine(word);
    

    输出

    "
    Joe
    wants
    to
    thank
    you
    !
    Here
    is
    another
    sentence
    ,
    where
    we
    will
    ...
    get
    this
    to
    work
    !
    Right
    now
    .
    "
    

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多