簡體   English   中英

Linq:在字符串中搜索所有多個空格

[英]Linq: Search a string for all occurrences of multiple spaces

我有一個字符串,我想找到所有多個空格出現的位置。 我正在寫一個標點符號檢查器。 我想使用並行linq來分離這個操作,但在此期間我只是尋找linq方法讓我開始。

繼Fredou的回答之后,正則表達式會做得很好。 Regex.Matches返回一個MatchCollection,它是一個(弱類型)Enumerable。 使用Cast <T>擴展后,這可以是Linq-ified:

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;

這將為您提供出現多個空格的所有起始索引。 它很漂亮,但我很確定它有效。

編輯:沒有必要加入。 這個更好。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM