Skip to content

Instantly share code, notes, and snippets.

@jimmy087
Created May 4, 2013 05:48
Show Gist options
  • Save jimmy087/5516367 to your computer and use it in GitHub Desktop.
Save jimmy087/5516367 to your computer and use it in GitHub Desktop.
Count each letter in the string
public class CountEachLetter {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter the string: ");
String s = input.nextLine();
// Invoke the countLetters method to count each letter
int[] counts = countLetters(s.toLowerCase());
//Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1) ? " time." : " times."));
}
}
}
// Count each letter in the string
private static int[] countLetters(String s) {
int [] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i))) {
counts [s.charAt(i) - 'a']++;
}
}
return counts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment