How would you count occurrences of a string within a string?

$1 Bitcoin bounty has been announced by author.
$2.23 has been already awarded by author.
$0 remains available.

I am doing something where I realised I wanted to count how many /s I could find in a string, and then it struck me, that there were about several ways to do it, but couldn't decide on what the best (or easiest) was.

At the moment I'm going with something like:

string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;

But I don't like it at all, any takers?

I don't really want to dig out RegEx for this, do I?

EDIT I: I know my string is going to have the term I'm searching for, so you can assume that...

EDIT II: Of course for strings where length > 1,

string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - source.Replace(needle,"").Length ) / needle.Length
Tags: ,

Good question

Catch more money :)

Send tips to you



0 answers - total earned - 0 BTC ($0 USD)

Everyone, even non-registered users could send Bitcoin Tips to YOU if they are inspired by your answer!

Post Answer

Will Bitcoin Tipping become a new Internet Culture?

Please share our story! THANK YOU!