从字符串JAVA

时间:2015-08-02 10:20:31

标签: java string character sequence trim

输入就像,

  

hiii,我非常喜欢java soooo

,预期的输出就像

  

嗨,我非常喜欢java

我的模糊编码如下,

List<String> wordList = Arrays.asList(word.split(""));
String previousCharacter;
boolean inneFlag = false;
boolean flag = false;
int iterator = 0;
int characterIterator = 0;
String finalizedWord = "";
previousCharacter = wordList.get(0);
for(String character : wordList){
    if((wordList.size()-1)==characterIterator){
          inneFlag = true;
     }
     if(flag){
         if(character.equalsIgnoreCase(previousCharacter)){
              iterator++;
              if(inneFlag){
                   if(iterator>2){
                        finalizedWord = finalizedWord.substring(0,(finalizedWord.length()-iterator));
                    }
               }
         }else{
              previousCharacter = character;
              if(iterator>=2){
                  finalizedWord = finalizedWord.substring(0,(finalizedWord.length()-iterator));
              }
              iterator = 0;
           }
       }else{
            flag = true;
       }
    characterIterator++;
    finalizedWord += character;
}

任何人都可以提供更好的解决方案吗?

1 个答案:

答案 0 :(得分:5)

一个简单的正则表达式将完成这项工作。

string.replaceAll("([A-Za-z])\\1+", "$1");

string.replaceAll("(.)\\1+", "$1");

DEMO