public static String compress(String original) {
int count = 1;
char currentChar = original.charAt(0);
String newString = "";
for (int x = 1; x < original.length(); x++) {
if (currentChar == original.charAt(x)) {
count++;
} else {
if (count == 1) {
newString += Character.toString(currentChar);
} else {
newString += Integer.toString(count) + Character.toString(currentChar);
}
count = 1;
}
currentChar = original.charAt(x);
}
return newString;
}
My code above is supposed to encode a string using RLE, so if a string is sssWWwRttty
the program should return 3s2WwR3ty
. The problem I'm running into is that the return value ignores the last character in the string. For example, if the argument for the compress method was sssWWwRttty
the return value would be 3s2WwR3t
or if the agument was qwwwEErtttyyyyy
the return value would be q3w2Er3t
. Does anyone see where I could be missing something for it to be excluding that portion of the string?