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
2010-09-20 23:37:51
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
2010-09-20 23:41:05
+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
2010-09-20 23:42:52
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
2010-09-20 23:47:33
I would have if I could (started the question with 49 rep, 1 under what I needed.
Crag
2010-09-20 23:49:25
Nvm, I got it to work.
Infodayne
2010-09-21 00:50:14
+1
A:
var str = "Count, the, commas,,, !";
var answer = str.Length - str.Replace(",", "").Length;
zerkms
2010-09-20 23:45:19
Technically speaking, the `Replace` will cause unnecessary shifts in memory.
Josh Stodola
2010-09-20 23:51:42
@Josh Stodola: Yup, I've just posted "yet another possible way to do that"
zerkms
2010-09-20 23:53:40
+6
A:
Here's the obligatory LINQ answer:
Dim cnt As Integer = yourString.Count(Function(ch) ch = ","c)
Jay Riggs
2010-09-20 23:46:10
+1 - These expressions just look a whole lot cooler!!! and take up a whole lot less real estate.
rockinthesixstring
2010-09-20 23:49:23
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
2010-09-21 00:24:27
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
2010-09-20 23:49:20
Point taken, I updated the example. My original point still stands.
Babak Naffas
2010-09-21 00:17:47
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
2010-09-21 00:02:24