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?
Python String count() The count() method returns the number of occurrences of a substring in the given string.
Total number of substrings = n + (n - 1) + (n - 2) + (n - 3) + (n - 4) + ……. + 2 + 1. So now we have a formula for evaluating the number of substrings where n is the length of a given string.
count() Python: Using Strings. The count() method can count the number of occurrences of a substring within a larger string. The Python string method count() searches through a string. It returns a value equal to the number of times a substring appears in the string.
Regex.Matches(input, "true").Count
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With