How to count the number of occurrences of a character in a String in java?
character count in a String in java
package com.tech.mindclues; import java.util.Scanner; public class StringCharCount { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the String : "); String str = sc.nextLine(); System.out.println("Enter the character to find the count: "); String findStr = sc.next(); int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = str.indexOf(findStr, lastIndex); if (lastIndex != -1) { count++; lastIndex += findStr.length(); } } System.out.println(count); } }
Enter the String : abcdeadashfkoraa Enter the character to find the count: a 5
post a comment