tags:

views:

144

answers:

7

I need a code to count how many commas there are in a richtextbox line. If there are 4 or more commas then do something, else delete line.

+2  A: 

It's C#, but you could do something like this:

int count = 0;

foreach(char c in string)
{
    if(c == ',') count++;
}

return count;
Dan at Demand
A: 

what about this:

string test = "abc,123,dfg";
int count = test.Split(',').length - 1;

sorry i'm a c# guy. Here is vb.net (i think):

Dim test As String = "abc,123,dfg"
Dim count As Integer = test.Split(',').length - 1
Abe Miessler
+4  A: 
    Dim str As String = "Count, the, commas,,, !"

    Dim count As Integer = 0

    For Each c As Char In str
        If c = "," Then
            count += 1
        End If
    Next

Vote up Dan @ Demand's answer, this is just the VB.Net version.

Crag
You should have put a [link to Dan's answer](http://stackoverflow.com/questions/3756262/count-how-many-commas-are-in-a-line/3756292#3756292). LE: if you could...
Cristian Ciupitu
I would have if I could (started the question with 49 rep, 1 under what I needed.
Crag
Nvm, I got it to work.
Infodayne
+1  A: 
var str = "Count, the, commas,,, !";
var answer = str.Length - str.Replace(",", "").Length;
zerkms
Technically speaking, the `Replace` will cause unnecessary shifts in memory.
Josh Stodola
@Josh Stodola: Yup, I've just posted "yet another possible way to do that"
zerkms
+6  A: 

Here's the obligatory LINQ answer:

Dim cnt As Integer = yourString.Count(Function(ch) ch = ","c)
Jay Riggs
+1 - These expressions just look a whole lot cooler!!! and take up a whole lot less real estate.
rockinthesixstring
However, just because you can't see the implementation doesn't mean it isn't costing you. In this case, not too bad; linear-time, which really can't be improved on for an "unordered" indexed collection like a string. However, there are some Linq one-liners that look very elegant but execute several orders of magnitude slower than an efficient iterative solution.
KeithS
A: 
if( new RegEx(",").Match(s).Matches.Count > 4 ){
    //insert logic here
}

I'm doing this off the top of my head so don't kill me if it's not perfect code, but you get the gist of what i'm doing. You can leverage a regular expression to tell you exactly how many commas there are and to perform the required logic if the condition is met.

Babak Naffas
you've lost the source string
zerkms
Point taken, I updated the example. My original point still stands.
Babak Naffas
No question would be complete without a RegEx solution.
Jim Mischel
A: 

This will actually give the required result (i.e. a string with the invalid lines removed):

Dim lines As String() = richTextBox.Text.Split(vbCrLf)
Dim validLines = lines.Where(Function(l) l.Count(Function(c) c = ","c) = 4)
Dim results As String = String.Join(vbCrLf, validLines)
Bennor McCarthy