counting against how many times a letter appears in a string java code example
Example 1: java count frequency of characters in a string
public class Frequency
{
public static void main(String[] args) {
String str = "picture perfect";
int[] freq = new int[str.length()];
int i, j;
char string[] = str.toCharArray();
for(i = 0; i <str.length(); i++) {
freq[i] = 1;
for(j = i+1; j <str.length(); j++) {
if(string[i] == string[j]) {
freq[i]++;
string[j] = '0';
}
}
}
System.out.println("Characters and their corresponding frequencies");
for(i = 0; i <freq.length; i++) {
if(string[i] != ' ' && string[i] != '0')
System.out.println(string[i] + "-" + freq[i]);
}
}
}
Example 2: 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 3: java get how many letters in a string
String str = "a string";
int length = str.length( );