Groups of two words in a phrase. C#

How do I know how many groups of two words exist in a phrase?

this is my Code

        var str = "word1 word2 word3 word4 word5";

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

The result should be: 2 because word1 and word2 is a group and word3 and word4 is other group, word5 is not part of any group

Exists a regex pattern for solve this problem?


Using regex solution.

Will match only words with [a-zA-Z0-9_] Also neglecting any multiple spaces

Example :

 string para= "word1    word2 word3 word4 word5"; // <= include multiple splaces
 Regex reg = new Regex(@"w+");

 Console.WriteLine((reg.Matches(para).Count) /2);  

Output :

2

Actually you don't need Regex, you can can find spaces count and divide by 2:

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

If it contains more than one space , then you can try Split() method overload which takes StringSplitOptions as a second parameter with the value RemoveEptryEntries . Then the return value does not include array elements that contain an empty string:

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

Use the below regex and then count the number of matches.

@"S+s+S+"

S+ matches one or more non-space characters where s+ matches one or more space characters.

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

链接地址: http://www.djcxy.com/p/51390.html

上一篇: 如何使用SSIS从列字符串中删除平面文件中的单词

下一篇: 一个短语中的两个单词组。 C#