In some interviews or exams, a problem is provided to the interviewee or student to find out the occurrence of the character in a string. In this example, I will help you in solving that problem/program with the easiest approach.
string Statement = ""; Console.WriteLine("Enter
a string to find number of Occurrence of a character"); Statement = Console.ReadLine(); //Converting the Statement to lowercase which help in counting
of the character in the string //As C# is Case-Sensitive Statement = Statement.ToLower(); //Check the length of string entered by the user if (Statement.Length>0) { //Iterate till length of statement is greater than zero //Here we check each character occurrence //Once count is checked, we will remove that character from the
string while (Statement.Length > 0) { //CountCharacter to store the character occurrence int CountCharacter = 0; Console.Write("Number of Occurance of '"+Statement[0] + "': "); //Checking the Character occurrence in the string entered by the
user for (int i=0;i<Statement.Length;i++) { if (Statement[0]==Statement[i]) { CountCharacter++; } } //Displaying the Count of each character
Console.Write(CountCharacter+"\n"); //Removing that character from the string Statement =
Statement.Replace(Statement[0].ToString(), string.Empty); } } //Console.ReadLine() to hold the screen after the execution of
the program Console.ReadLine(); |
0 comments:
Post a Comment