elkostek elkostek - 9 days ago 5
Java Question

Change sysout to String

please for help
I need retrurn in 'String dst;' the same result as console

e.g. input

txt = "aabbc";
which gives
return dst = "a2b2c1"


public String compres(String txt) {

String dst = "";
char character;
int count;

for (int i = 0; i < txt.length(); i++) {
character = txt.charAt(i);
count = 1;
while (i < txt.length() - 1 && txt.charAt(i + 1) == character) {
count++;
i++;
}
System.out.print(character);
System.out.print(count);
}
return dst;
}

Answer

Use StringBuilder.

public String compres(String txt) {

        StringBuilder dst = new StringBuilder();
        char character;
        int count;

        for (int i = 0; i < txt.length(); i++) {
            character = txt.charAt(i);
            count = 1;
            while (i < txt.length() - 1 && txt.charAt(i + 1) == character) {
                count++;
                i++;
            }
            System.out.print(character);
            System.out.print(count);
            dst.append(character).append(count);
        }

        return dst.toString();
}