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.
Asked
Active
Viewed 1,057 times
3 Answers
6
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
- 117,338
- 33
- 229
- 351
-
could you bend this easily to return the number of spaces found? – Aran Mulholland Apr 29 '10 at 00:14
-
http://stackoverflow.com/questions/541954/how-would-you-count-occurences-of-a-string-within-a-string-c – Raj Kaimal Apr 29 '10 at 00:14
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;
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;

mrmcgreg
- 2,754
- 1
- 23
- 26
-
Your code is ugly, but it runs 5 times faster than the Regex method! +1 – spender Apr 29 '10 at 01:45
-
Very, very ugly :). I'm not sure how PLINQ handles it. It would be interesting to see if you get any speedup on multiple cores. – mrmcgreg Apr 29 '10 at 02:01