Replace multiple consecutive occurrences of a character with a single occurrence

后端 未结 5 585
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 14:47

I am making a natural language language processing application in Java, I am using data from IMDB and Amazon.

I came across a certain dataset which has words like

5条回答
  •  没有蜡笔的小新
    2021-01-07 15:28

    You can use this snippet its quite fast implementation.

    public static String removeConsecutiveChars(String str) {
    
            if (str == null) {
                return null;
            }
    
            int strLen = str.length();
            if (strLen <= 1) {
                return str;
            }
    
            char[] strChar = str.toCharArray();
            char temp = strChar[0];
    
            StringBuilder stringBuilder = new StringBuilder(strLen);
            for (int i = 1; i < strLen; i++) {
    
                char val = strChar[i];
                if (val != temp) {
                    stringBuilder.append(temp);
                    temp = val;
                }
            }
            stringBuilder.append(temp);
    
            return stringBuilder.toString();
        }
    

提交回复
热议问题