Count all occurrences of a character in a string

  • Thread starter Thread starter thomaz
  • Start date Start date
T

thomaz

Hi....

There is a string method to count the total number of a
specified character in a string.
EX: count the total of (*) in a string
*** Test ***

Thanks....
 
I would recommend a manual approach, looping through each character in the
string.

This example could be optimized more.
public static int CountChar ( string input, char c )
{
int retval = 0;
for (int i = 0; i < input.Length; i ++)
if (c == input )
retval ++;
return retval;
}
 
thomaz said:
There is a string method to count the total number
of a specified character in a string.

private static int CountChar(char c, string s)
{
int pos = 0, count = 0;

while ((pos = s.IndexOf(c, pos)) != -1)
{
count++;
pos++;
}

return count;
}

P.
 
thomaz said:
There is a string method to count the total number of a
specified character in a string.
EX: count the total of (*) in a string
*** Test ***

This is a nice way, IMO:

public class StringHelper
{
public static int CountOccurencesOfChar(string instance, char c) {
int result = 0;
foreach (char curChar in instance) {
if (c == curChar) {
++result;
}
}
return result;
}
}
 
Back
Top