Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you count occurrences of a string (actually a char) within a string?

Tags:

string

c#

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 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?

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

Of course for strings where length > 1,

string haystack = "/once/upon/a/time"; string needle = "/"; int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length; 
like image 562
Ian G Avatar asked Feb 12 '09 15:02

Ian G


People also ask

How do I count the number of occurrences of a char in a string?

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

How do you count a string occurrence in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.


1 Answers

If you're using .NET 3.5 you can do this in a one-liner with LINQ:

int count = source.Count(f => f == '/'); 

If you don't want to use LINQ you can do it with:

int count = source.Split('/').Length - 1; 

You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:

Your original = 12s
source.Count = 19s
source.Split = 17s
foreach (from bobwienholt's answer) = 10s

(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)

like image 199
LukeH Avatar answered Dec 11 '22 06:12

LukeH