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

Answer

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

All string Questions

Ask your interview questions on string

Write Your comment or Questions if you want the answers on string from string Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---