469,358 Members | 1,585 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,358 developers. It's quick & easy.

String.Contains Count?

Can anyone point me in the direction of functionality that will provide the number of times a String contains a given substring? Preferably in C# and/or built in to the .Net framework...
Jul 24 '07 #1
3 2949
Plater
7,872 Expert 4TB
There's probably a better way to do this (Such as the overloads for .IndexOf()... ) but whatever.
Expand|Select|Wrap|Line Numbers
  1. string n="freddrandr";
  2.  
  3. int count=0;
  4. for(int i=0;i<n.length;i++)
  5. {
  6.    if (n.SubString(i).StartsWith("dr"))
  7.    {
  8.       count++;
  9.    } 
  10. }
  11. //count will be 2
  12.  
Jul 24 '07 #2
Thanks for your help.
Aug 8 '07 #3
For anyone interested, this is what I ended up using:
public Int32 ContainsCount(String SearchPhrase, String SearchText) {
String Remains = SearchText;
Int32 NewIndex = 0;
Int16 Count = 0;
while (Remains.Length >= SearchPhrase.Length)
{
NewIndex = Remains.IndexOf(SearchPhrase);
if (NewIndex >= 0)
{
Count++;
Remains = Remains.Substring(NewIndex + SearchPhrase.Length);
}
else
{
return Count;
}
}
return Count;
}
Aug 8 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

13 posts views Thread by nishit.gupta | last post: by
reply views Thread by Borse, Ganesh | last post: by
4 posts views Thread by Jeff | last post: by
1 post views Thread by Jon Skeet [C# MVP] | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.