Java Program to Count the Occurrences of Each Character and Each Word in String.

import java.util.HashMap;
public class CharOccurance {
public static void main(String[] args) {

charCount("ramram");
wordCount("ram ram");


public static void charCount(String s1) {
    int counter[] = new int[256];
    for (int i = 0; i < s1.length(); i++) {
        counter[(int) s1.charAt(i)]++;
    }
    for (int i = 0; i < 256; i++) {
        if (counter[i] != 0) {
            System.out.println((char) i + " --> " + counter[i]);
        }
    }
}

public static void wordCount(String s1) {
    String[] s2 = s1.split(" ");
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (int i = 0; i < s2.length; i++) {
        if (map.containsKey(s2[i])) {
            int count = map.get(s2[i]);
            map.put(s2[i], count + 1);
        } else {
            map.put(s2[i], 1);
        }
    }
    System.out.println(map);
}

}

There are no comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Start typing and press Enter to search

Shopping Cart

No products in the cart.