tags:

views:

313

answers:

7

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?

+11  A: 
Regex.Matches( input,  "true" ).Count
BioBuckyBall
Based on brevity alone - you win ;)
onekidney
+2  A: 

Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;

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

Casper
A: 

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
+1  A: 

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
+6  A: 

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 Regex = @"\btrue\b";
int NumberOfTrues = Regex.Matches(SearchText, Regex).Count;

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

DonaldRay
A: 

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
ha ha - I should mark yours as correct just for using my proposed method name. :)
onekidney
A: 

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