2010-04-29 47 views

回答

6

而且更好地Fredou的答案,正則表達式將很好地做到這一點。 Regex.Matches返回一個MatchCollection,它是一個(弱類型)Enumerable。這可以通過Cast<T> extension後的LINQ指明分數:

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

+1謝謝,我不擅長與正則表達式:-) – Fredou 2010-04-29 00:13:44

+0

你可以彎曲這容易返回找到的空格的數量? – 2010-04-29 00:14:05

+0

http://stackoverflow.com/questions/541954/how-would-you-count-occurences-of-a-string-within-a-string-c – 2010-04-29 00:14:49

2

,這將是與正則表達式

2
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; 
+0

你的代碼很醜,但它運行速度比正則表達式快5倍! +1 – spender 2010-04-29 01:45:18

+0

非常非常難看:)。我不確定PLINQ如何處理它。看看你是否在多核上獲得任何加速會很有趣。 – mrmcgreg 2010-04-29 02:01:14

相關問題