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

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

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: ,
User rating:

Good question

User rating:
User rating:

Catch more money :)

User rating:

Send tips to you

1111

User rating:
qwert
User rating:
User rating:
User rating:
User rating:
User rating:
User rating:
User rating:

0 answers

0
=
0
=
$0
Internet users could send Bitcoin Tips to you if they like your answer!

Too many commands? Learning new syntax?

FavScripts.com is a free tool to save your favorite scripts and commands, then quickly find and copy-paste your commands with just few clicks.

Boost your productivity with FavScripts.com!

Post Answer