简体   繁体   中英

Linq: Search a string for all occurrences of multiple spaces

I have a string and i want to find the position of all the occurrences of multiple spaces. Im writing a punctuation checker. I would like to parralelise this operation using parallel linq but in the meantime im just looking for the linq method to get me started.

Further to Fredou's answer, a Regex would do this nicely. Regex.Matches returns a MatchCollection that is a (weakly typed) Enumerable. This can be Linq-ified after using the Cast<T> extension :

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

使用正则表达式会更好

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;

That will give you all of the starting indices where multiple spaces occur. It's pretty but I'm pretty sure that it works.

edit: There's no need for the join. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM