Linq: search string for all occurrences of multiple spaces

I have a string and I want to find the position of all occurrences of multiple spaces. I am writing a punctuation check. I would like to paralyze this operation using parallel linq, but for now I'm just looking for a linq method to get started.

+2


a source to share


3 answers


In addition to Fredou's answer, Regex will do it nicely. Regex.Matches returns a MatchCollection, which is a (weakly typed) Enumerable. It could be Linq-ified after using Cast <T> extension :



Regex.Matches(input,@" {2,}").Cast<Match>().Select(m=>new{m.Index,m.Length})

      

+6


a source


it would be better with regex



+2


a source


var s = from i in Enumerable.Range(0, test.Length)
                    from j in Enumerable.Range(0, test.Length)
                    where test[i] == ' ' && (i == 0 || test[i - 1] != ' ') &&
                    (test[j] == ' ' && j == (i + 1))
                    select i;

      

This will give you all the leading indices where multiple spaces occur. It's pretty, but I'm pretty sure it works.

edit: no connection needed. This is better.

  var s = from i in Enumerable.Range(0, test.Length-1)
                where test[i] == ' ' && (i == 0 || test[i - 1] != ' ') && (test[i+1] == ' ')
                    select i;

      

+2


a source







All Articles