Jorge Lopez Jr
Jorge Lopez Jr

Reputation: 257

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)) {
            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?

Upvotes: 1

Views: 2050

Answers (1)

MrSmith42
MrSmith42

Reputation: 10151

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.

Upvotes: 2

Related Questions