Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of times a string appears within a string [duplicate]

Tags:

string

c#

count

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?

like image 862
Paul Mignard Avatar asked Jun 10 '10 16:06

Paul Mignard


People also ask

How do you count the number of times a string appears in a string?

Python String count() The count() method returns the number of occurrences of a substring in the given string.

How do you count the number of substrings in a 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.

How do you count the number of times a word appears in a string in Python?

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.


2 Answers

Regex.Matches(input, "true").Count 
like image 129
µBio Avatar answered Sep 23 '22 08:09

µBio


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;     } } 
like image 31
rjdevereux Avatar answered Sep 21 '22 08:09

rjdevereux