How many time input letter appear in given string in C# ?

By

How Many input in String in C#
Now i am here to program some intresting C# code.You have to just copy and execute the C# code in your development enviroment.This C# program is  like below

User input the letter & string and you have to write a program that is how many time this letter coming in input string.Please have a look for C# code.

Code Sample [C# Code]
using System;
                                 
public class Program
{
       public static void Main()
       {
          string inputString="";
          char inputChar ;
          Console.WriteLine("Please input the string");
          inputString=Console.ReadLine();
          outer:
           Console.WriteLine("Please input the character which you want to count");
              string a =Console.ReadLine();
              if(a.Length==1)
              {
            inputChar =Convert.ToChar(a);
              }  
              else
              {
                     Console.WriteLine("Wrong input only one character allowed");
                     goto outer;
              }
       int count = GetLetterCountInSentence(inputChar, inputString);
       Console.WriteLine("letter {0} found {1} Times in '{2}'",inputChar,count, inputString);
       Console.ReadLine();
    }
       public static int GetLetterCountInSentence(char letter, string string2check)
        {
            int noOfTimes=0;
            for (int i = 0; i < string2check.Length; i++)
            {
                if (string2check[i] == letter)//if found, increase the count
                {
                    noOfTimes += 1;
                }
            }
            return noOfTimes; //returns the count of noOfTimes
        }

}

Output
Output looks like below.
Please input the string
> my name is code by topic
Please input the character which you want to count
>c
letter c found 3 Times in my name is code by topic

Explanation
In above i create a method name is GetLetterCountInSentence its take 2 argument first is letter which you want to count and second is string which i have to check. Here i also use the go to statement because user if input more than 1 character then its show error message and again statement to goes for input the new charachter.
read more..

1 comment: