1

Basically I am reading a string patterned like AABBCCAACC; how can I count how many times has each group of 2 characters been typed in by the user?

I have tried this without success:

for (int i = 1; i < str.length(); i+=2) {
  if(str.substring(i, i+1) == "AA");
  {
    countAA++;
  }
}
assylias
  • 321,522
  • 82
  • 660
  • 783
Arrmin
  • 33
  • 5
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – cegredev May 02 '20 at 15:34
  • What if you have String like `AAAA`? How many `AA` does it hold? 2 or 3? – Pshemo May 02 '20 at 15:40
  • BTW `.substring(i, i+1)` may return only one character, if you want return two characters use `i+2` instead of `i+1`. – Pshemo May 02 '20 at 15:40

2 Answers2

2

You can iterate over the characters and save the occurence of each character and the one after it in a hashmap as follows:

public static void main(String[] args) {
    String str = "AABBCCAACC";
    System.out.println(getOccurences(str));
}
private static HashMap<String,Integer> getOccurences(String str) {
    HashMap<String,Integer> map = new HashMap<>();
    if(!str.isEmpty() && str.length()>1) {
        char[] characters = str.toCharArray();
        for(int i = 0; i < characters.length-1; i++) {
            String current = ""+characters[i]+characters[i+1];
            if(map.containsKey(current))
                map.replace(current, map.get(current)+1);
            else
                map.put(current,1);
        }
    }
    return map;
}

The output here would be:

{AA=2, BB=1, CC=2, AB=1, BC=1, AC=1, CA=1}
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

You can use Map for this task:


    public static void main(String[] args) {
        String str = "AABBCCAACC";
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length() - 1; i++) {
            String key = "" + str.charAt(i) + str.charAt(i + 1);
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        System.out.println(map);
    }

, output

{AA=2, BB=1, CC=2, AB=1, BC=1, AC=1, CA=1}
0xh3xa
  • 4,801
  • 2
  • 14
  • 28