Using linq to count substrings in a string?

I could use the following linq expression to count the number of occurrences of a word as follows:

string test = "And And And"; int j = test.Split(' ').Count(x => x.Contains("And")); 

However, what if I was looking for "And And", is there a way to use linq to count words without using split. Does any of these methods take longer O (n) time?

+4
source share
3 answers

You can use regex:

 string test = "And And And"; int j = Regex.Matches(test, "And").Cast<Match>().Count(); 

By the way, do you want to allow overlapping occurrences? those. if you are looking for an AND, do you think that test contains 1 or 2 occurrences of it?

+5
source

You can use IndexOf :

 string what = "And"; int count = 0; int pos = -what.Length; for (;;) { pos = input.IndexOf(what, pos + what.Length); if (pos == -1) break; count++; } 
0
source

This is not exactly Linq, but you can also make an extension method as shown below. This is probably more efficient than any Linq solution:

  public static int CountSubStrings(this string input, string delimiter, bool ignoreCase = false) { int instancesNo = 0; int pos = 0; while((pos = input.IndexOf(delimiter, pos, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture)) != -1) { pos += delimiter.Length; instancesNo++; } return instancesNo; } 
0
source

Source: https://habr.com/ru/post/1394795/


All Articles