将sysout更改为String

时间:2016-11-30 21:12:05

标签: java

请求帮助 我需要重新开始'String dst;'与控制台相同的结果 例如
输入txt = "aabbc";,其中包含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;
}

2 个答案:

答案 0 :(得分:1)

使用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();
}

答案 1 :(得分:0)

今天我的伴侣给了我最简单的解决方案,我只需要在我的循环中添加:

dst + = character +“”+ count;

而不是double sysout