Saved Bookmarks
| 1. |
Is it possible to count the number of times a given character appears in a String? |
|
Answer» The charAt() method of the String class can be USED to find out the number of times a specified character appears in a string. Below is a Java program to check the occurrences of a specified character in a string. public class CkeckforOccurences{ public static void main(String[] args) { String str= "InterviewBit"; char ch = 'e'; //character to look for occurrences is e INT COUNT = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { count++; } } System.out.println("The character '" + ch + "' appears " + count + " times in the given string '" + str + "'."); }}The character 'e' appears 2 times in the given string 'InterviewBit'.As you can see, the above program checks how many times the character ch OCCURS in the string str. Whenever we encounter the character ch in the string, we increase the count by one. Finally, we print the total character count at the end. |
|