Java String Manipulation : Comparing adjacent Characters in Java

前端 未结 12 823
陌清茗
陌清茗 2021-01-07 10:57

i have the following problem
Given a string, return a \"cleaned\" string where adjacent chars that are the same have been reduced to a single char. So \"yyzzza\"

12条回答
  •  余生分开走
    2021-01-07 11:23

    I would do it like this:

    public static String stringClean(String str) {
        if (str == null || "".equals(str))
            return str;
        StringBuffer buffer = new StringBuffer();
        char[] chars = str.toCharArray();
        buffer.append(chars[0]);
        for (int i = 1; i < chars.length; i++) {
            if (chars[i] != chars[i-1])
                buffer.append(chars[i]);
        }
        return buffer.toString();
    }
    

提交回复
热议问题