Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting Instances of a Character in a String

Status
Not open for further replies.

Signit

MIS
Oct 17, 2003
114
US
I am trying to count the number of semicolons ; in a string. I have tried a variety of methods to no avail in that each way I have tried I only get the length of the string returned.

Code:
// one attempted method
for (int i = 0; i < v_myIngredients.Length; i++)
{
  if(String.Equals(v_myIngredients.Substring(v_myIngredients.IndexOf(";")),";"))
  {
    listCount++;
  }
}

// other attempted method
for (int i = 0; i < v_myIngredients.Length; i++)
{
  if(v_myIngredients.Substring(v_myIngredients.IndexOf(";")==";"))
  {
    listCount++;
  }
}

Neither way has worked. Any suggestions would be apprecaited. I think it might be because I am just comparing objects of type eg IF sees both as being characters so therefore it says it's true and moves on.
 
You can use RegularExpressions for this. you will need to import the System.Text.RegularExpression namespace.
Code:
Regex r = new Regex(";");
MatchCollection mc = r.Matches(stringToMatch);
int matches = mc.Count;

Hope this helps

Rob

Go placidly amidst the noise and haste, and remember what peace there may be in silence - Erhmann 1927
 
Thanks for the tip. I ended up doing this this morning:

Code:
for (int i = 0; i < v_myIngredients.Length; i++)
{
  if(v_myIngredients.Substring(i,1)==";")
  {
    listCount++;
  }
}
 
The above function is working but no so performant.
Here is improved one:
Code:
public int CountOcc2(string s, char ch)
{   int iCount=0;
    for (int i=0;i<s.Length;i++)
	{
	   if (s[i]==ch) 
		iCount++;
	}
    return iCount;
}
int count1=CountOcc2("a;blabla;ccccc;d",';');

-obislavu-
 
obislavu -

This is an unusual case, but it is possible for it to happen: the string may contain a Unicode surrogate character. When it does, using an indexer to go through the string is likely to fail. In that case, you'll want to do something like this:
Code:
public int CountOcc3(string s, char ch)
{
   int iCount=0;
   CharEnumerator ce = s.GetEnumerator();
   while (ce.MoveNext())
   {
      if (ce.Current == ch)
        iCount++;
   }
   return iCount;
}
Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Code:
int count = foo.Length - foo.Replace( ";", "" );
That should work too, but I don't know what solution runs the fastest.
 
Correction:
Code:
int count = foo.Length - foo.Replace( ";", "" ).Length;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top