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