views:

190

answers:

3

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.

+2  A: 

this would be better with regex

Fredou
+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
+1 thanks, I'm not good at all with regex :-)
Fredou
could you bend this easily to return the number of spaces found?
Aran Mulholland
http://stackoverflow.com/questions/541954/how-would-you-count-occurences-of-a-string-within-a-string-c
Raj Kaimal
Bent enough? ;)
spender
working like a charm, thanks
Aran Mulholland
+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
Your code is ugly, but it runs 5 times faster than the Regex method! +1
spender
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.
Cole