DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

.NET Program to count the number of occurrences of a Character in a String

By Ashok Nalam on 24 Jun 2013 | Category: C# | Tagged: .NET string 
The program returns number of occurrences of a particular character in a String.
  Discuss Add Comment   |  
Add rating Rate this resource   

The program returns number of occurrences of a particular character/letter in a string/sentence.

E.g: "HELLO WORLD" - character 'L'  count = 3

Program:

namespace DotNetMirror
{
    class NoOfTimesLetterAppearedInSentence
    {
        public static void Main()
        {
            char letterToFind = 'r';
            string sentence = "dotnetmirror reflects your knowledge";
            int count = GetLetterCountInSentence(letterToFind, sentence);
            Console.WriteLine("letter '{0}' found {1} times in '{2}'",letterToFind,count, sentence);
            Console.ReadLine();
        }
        public static int GetLetterCountInSentence(char letter, string sentence2check)
        {
            int noOfTimes=0;
            for (int i = 0; i < sentence2check.Length; i++)
            {
                if (sentence2check[i] == letter)
                {
                    noOfTimes += 1; //if found, increase the count
                }
            }
            return noOfTimes; //returns the count of noOfTimes
        }
    }
}

Output:

letter 'r' found 5 times in 'dotnetmirror reflects your knowledge'
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 8586  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.