简体   繁体   中英

Removing sequence character from string JAVA

The input will be like,

hiii, i love java soooo much

and the expected output will be like

hi, i love java so much

For my vague coding is as follows,

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;
}

Can anyone give better solution??

A simple regex will do this job.

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

or

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM