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.
+5
A:
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})
spender
2010-04-29 00:11:24
+1 thanks, I'm not good at all with regex :-)
Fredou
2010-04-29 00:13:44
could you bend this easily to return the number of spaces found?
Aran Mulholland
2010-04-29 00:14:05
http://stackoverflow.com/questions/541954/how-would-you-count-occurences-of-a-string-within-a-string-c
Raj Kaimal
2010-04-29 00:14:49
Bent enough? ;)
spender
2010-04-29 00:15:45
working like a charm, thanks
Aran Mulholland
2010-04-29 00:50:31
+2
A:
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;
Cole
2010-04-29 01:08:55