Counts the specified target in a String. - CSharp System

CSharp examples for System:String Search

Description

Counts the specified target in a String.

Demo Code

//   The MIT License (MIT)
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System;/*from  www. ja  v  a  2  s  .com*/

public class Main{
        /// <summary>
        /// Counts the specified target.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="character">The character.</param>
        /// <returns>Character count.</returns>
        public static int Count(string target, char character)
        {
            if (string.IsNullOrEmpty(target))
            {
                return 0;
            }

            int count = 0;
            for (int i = 0; i < target.Length; i++)
            {
                char c = target[i];
                if (c.CompareTo(character) == 0)
                {
                    count++;
                }
            }

            return count;
        }
}

Related Tutorials