Jorge Lopez Jr Jorge Lopez Jr - 1 year ago 119
Java Question

Run length encoding for java program

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)) {
} 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
the program should return
. 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
the return value would be
or if the agument was
the return value would be
. Does anyone see where I could be missing something for it to be excluding that portion of the string?

Answer Source

You never add currentChar in the last run of your loop to newString.

For performance I highly recommend to build your result in a StringBuilder instead of appending to a String. Appending to a String always creates a new String-Object which costs time and leads to a lot of object creation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download