java get count of character in string code example

Example 1: counting the number of characters in a string java

public static void main(String[] args) {
		int wordCount = 0;
		String word = "hill";
		for (char letter = 'a'; letter <= 'z'; letter++) {
			for (int i = 0; i < word.length(); i++) {
				if (word.charAt(i) == letter) {
					wordCount++;
				}
			}
			if (wordCount > 0) {
				System.out.println(letter + "=" + wordCount);
				wordCount = 0;
			}
		}
	}

Example 2: count the number of occurrences of a character in a string java

String line = "apples.oranges.bananas";
int count = line.length() - line.replace(".", "").length();
System.out.println(count);//displays 2

Tags:

Java Example