I am new to Java and am trying to create a method that will allow me to remove duplicate characters in a string and create a new string with all the consecutive occurrences of the same character turned into a single character. For example, string fffggghhh would return as fgh. I have provided my code below but I am receiving an index out of range error with the length of the string that I input. For example when testing this method and entering AA as my string, I receive an index out of range 2 error.
public String DuplicatesTEST(String s) {
StringBuilder result = new StringBuilder();
for (int i = 1; i <= s.length(); i++) {
char curr = s.charAt(i);
char prev = s.charAt(0);
if (curr != prev) {
result.append(prev);
} else if (curr == prev)
prev = curr;
}
return result.toString();
}