Count the number of lines appearing in a line

I just have a line that looks something like this:

"7, true, N. A., false: 67, false, N. A., false: 5, false, N. A., false: 5, false, N. A., false"

All I want to do is to count how many times the line true appears on this line. I feel the answer is something like String.CountAllTheTimesThisStringAppearsInThatString() , but for some reason I just can't figure it out. Help?

+42
string c # count
Jun 10 '10 at 16:48
source share
7 answers
 Regex.Matches(input, "true").Count 
+145
Jun 10 '10 at 16:53
source share

Probably not the most efficient, but I think this is an easy way to do this.

 class Program { static void Main(string[] args) { Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true")); Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false")); } static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find) { var s2 = orig.Replace(find,""); return (orig.Length - s2.Length) / find.Length; } } 
+14
Jun 10 '10 at 17:27
source share

Your regular expression should be \btrue\b to get around the "misunderstanding" problem that Casper raises. A complete solution would look like this:

 string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"; string regexPattern = @"\btrue\b"; int numberOfTrues = Regex.Matches(searchText, regexPattern).Count; 

Ensure that the System.Text.RegularExpressions namespace is included at the top of the file.

+12
Jun 10 '10 at 17:22
source share

This will fail, although if the string can contain strings of type "miscontrue".

  Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count; 
+5
Jun 10 2018-10-10
source share

With Linq ...

 string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"; var count = s.Split(new[] {',', ':'}).Count(s => s == "true" ); 
+3
Jun 10 '10 at 17:08
source share

Here I am redesigning the answer using LINQ. It just shows that there are more than β€œn” ways to cook an egg:

 public int countTrue(string data) { string[] splitdata = data.Split(','); var results = from p in splitdata where p.Contains("true") select p; return results.Count(); } 
+3
Jun 10 '10 at 17:46
source share

do this, note that you will need to define a regex for 'test' !!!

 string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"; string[] parts = (new Regex("")).Split(s); //just do a count on parts 
+2
Jun 10 '10 at 17:00
source share



All Articles