65

I simply have a string that looks something like this:

"7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"

All I want to do is to count how many times the string "true" appears in that string. I'm feeling like the answer is something like String.CountAllTheTimesThisStringAppearsInThatString() but for some reason I just can't figure it out. Help?

Milad Rashidi
  • 1,084
  • 4
  • 18
  • 35
Paul Mignard
  • 5,594
  • 6
  • 41
  • 60

7 Answers7

202
Regex.Matches(input, "true").Count
Chris Benard
  • 3,068
  • 2
  • 25
  • 34
µBio
  • 10,512
  • 6
  • 37
  • 55
16

Probably not the most efficient, but think it's a neat way to do it.

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;
    }
}
rjdevereux
  • 1,772
  • 2
  • 19
  • 35
14

Your regular expression should be \btrue\b to get around the 'miscontrue' issue Casper brings up. The full 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;

Make sure the System.Text.RegularExpressions namespace is included at the top of the file.

StuartLC
  • 100,561
  • 17
  • 199
  • 269
DonaldRay
  • 503
  • 3
  • 11
5

This will fail though if the string can contain strings like "miscontrue".

   Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;
Sangram Nandkhile
  • 16,457
  • 17
  • 78
  • 113
Sploofy
  • 503
  • 5
  • 13
4

Here, I'll over-architect the answer using LINQ. Just shows that there's 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();
}
Robaticus
  • 22,427
  • 5
  • 53
  • 63
3

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" );
Jace Rhea
  • 4,944
  • 4
  • 35
  • 55
2

do this , please note that you will have to define the 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
VoodooChild
  • 9,686
  • 7
  • 65
  • 99