All pastes #1188468 Raw Edit

count characters

public text v1 · immutable
#1188468 ·published 2008-08-29 12:57 UTC
rendered paste body
using System;

public static class CharacterCounter
{
	public static void Main(string[] args)
	{
		string joinedString = string.Join(" ", args);
		
		Console.WriteLine(CountCharacters('n', joinedString));
		Console.WriteLine(joinedString.CountCharacters('n'));
	}
	
	/// <summary>
	/// Extension method. Counts the number of times char c shows up in the current instance of a String
	/// </summary>
	/// <example>
	/// string s = "jerry";
	/// Console.WriteLine(s.CountCharacters('r'));
	/// </example>
	public static int CountCharacters(this string str, char c)
	{
		return CountCharacters(c, str);
	}

	/// <summary>
	/// Counts the number of times char c shows up in String str
	/// </summary>
	public static int CountCharacters(char c, string str)
	{
		int currentIndex = 0;
		int count = 0;
		
		while (str.IndexOf(c, currentIndex) > -1)
		{
			currentIndex = str.IndexOf(c, currentIndex) + 1;
			count++;
		}
		
		return count;
	}
}