432,028 Members | 1,092 Online
Need help? Post your question and get tips & solutions from a community of 432,028 IT Pros & Developers. It's quick & easy.

# Count all occurrences of a character in a string

 P: n/a 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.... Nov 16 '05 #1
4 Replies

 P: n/a You could use a regular expression. "thomaz" wrote in message news:18****************************@phx.gbl... 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.... Nov 16 '05 #2

 P: n/a 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 [i]) retval ++; return retval; } -- Regards, Dennis JD Myrén Oslo Kodebureau "thomaz" wrote in message news:18****************************@phx.gbl... 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.... Nov 16 '05 #3

 P: n/a "thomaz" wrote: 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. Nov 16 '05 #4

 P: n/a thomaz wrote: 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; } } Nov 16 '05 #5

### This discussion thread is closed

Replies have been disabled for this discussion.