Counts the total number of the occurrences of a character in the given string. - CSharp System

CSharp examples for System:Char

Description

Counts the total number of the occurrences of a character in the given string.

Demo Code

//  Copyright ? 2011, Grid Protection Alliance.  All Rights Reserved.
using System.Text.RegularExpressions;
using System.Text;
using System.IO;/*w  w  w .  ja  v a  2  s  . c  o m*/
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Counts the total number of the occurrences of a character in the given string.
        /// </summary>
        /// <param name="value">Input string.</param>
        /// <param name="characterToCount">Character to be counted.</param>
        /// <returns>Total number of the occurrences of <paramref name="characterToCount" /> in the given string.</returns>
        public static int CharCount(this string value, char characterToCount)
        {
            if (string.IsNullOrEmpty(value))
                return 0;

            int total = 0;

            for (int x = 0; x < value.Length; x++)
            {
                if (value[x] == characterToCount)
                    total++;
            }

            return total;
        }
}

Related Tutorials