Tuesday, April 24, 2018

Count the repeated character in a string !!

  1. public class CountOfCharacter {
  2. public static void main(String[] args) {
  3. String s = "abcabcabc";
  4. countOfRepeatedCharacter(s);
  5. }
  6. public static void countOfRepeatedCharacter(String s) {
  7. char c[] = s.toCharArray();
  8. Map<Character, Integer> map = new HashMap<Character, Integer>();
  9. for (int i = 0; i < c.length; i++) {
  10. if (map.containsKey(c[i])) {
  11. map.put(c[i], map.get(c[i]) + 1);
  12. } else {
  13. map.put(c[i], 1);
  14. }
  15. }
  16. System.out.println(map);
  17. }
  18. }
Output: 
{a=3, b=3, c=3}

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...