Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

31 July 2012

Program to find number of occurrences of a character/letter in a sentence in .NET


In this snippet we will see the program to find number of occurrences of a character in a sentence.

   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)//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'


0 Comments:

Post a Comment