Groovy web console

subscribe to the feed Subscribe
to this
site

test

Published 2 months ago by test with tags test
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
String stringToFormat = "abcaaabbb"

def isCharSame(def previousChar, def nextChar){
    return previousChar.equals(nextChar)
}


def stringCompression(String stringToFormat){
   String loweredCase = stringToFormat.toLowerCase()
    String finalString = ""
    def previousChar = ""
    int counter = 1
        for (int x=0; x<loweredCase.length(); x++){
            def nextChar = loweredCase.charAt(x)
            if(previousChar == nextChar && !(x == loweredCase.length()-1)){
                counter += 1
            }else{
                if(counter > 1){
                    finalString += ((x == loweredCase.length()-1))?"$counter":"$counter$nextChar"
                    counter = 1
                }else{
                    finalString += nextChar
                    counter = 1
                }
            }
            previousChar = nextChar
        }
        finalString
}


stringCompression(stringToFormat)