DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

number of occurrences of a character in a string in c#

By Ashok Nalam on 10 Sep 2013 | Category: C# | Tagged: string .NET 
In this snippet we will see the program to find number of occurrences of a character in a string.
  Discuss Add Comment   |  
Add rating Rate this resource   

Below programs shows number of occurrences of a character in a string.

class NoOfTimesLetterAppearedInString
{
    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)//if found, increase the count
            {
                noOfTimes += 1;
            }
        }
        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) : 9226  (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.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys