首页 文章

短语中的两个单词组 . C#

提问于
浏览
-1

我如何知道短语中存在多少组两个单词?

这是我的代码

var str = "word1 word2 word3 word4 word5";

        Console.WriteLine(str.CountGroupWords(2));
        Console.ReadKey();

结果应该是:2因为word1和word2是一个组而word3和word4是其他组,word5不是任何组的一部分

存在正则表达式模式来解决这个问题?

3 回答

  • 4

    使用正则表达式解决方案 .

    将只与 [a-zA-Z0-9_] 匹配的单词也忽略任何多个空格

    示例:

    string para= "word1    word2 word3 word4 word5"; // <= include multiple splaces
     Regex reg = new Regex(@"\w+");
    
     Console.WriteLine((reg.Matches(para).Count) /2);
    

    输出:

    2
    
  • 0

    其实你不需要正则表达式,你可以找到空格数并除以2:

    var result = str.Count(x => x == ' ') / 2;
    

    If it contains more than one space ,然后你可以尝试Split()方法重载,它将StringSplitOptions作为第二个参数,值为 RemoveEptryEntries . 然后返回值不包含包含空字符串的数组元素:

    var result = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length / 2;
    
  • 2

    使用以下正则表达式,然后计算匹配数 .

    @"\S+\s+\S+"
    

    \S+ 匹配 \s+ 与一个或多个空格字符匹配的一个或多个非空格字符 .

    DEMO

    String input = @"word1 word2 word3 word4 word5";
    Regex rgx = new Regex(@"\S+\s+\S+");
    int NumberOfTrues = rgx.Matches(input).Count;
    Console.WriteLine(NumberOfTrues);
    

    IDEONE

相关问题