Method to Remove Consecutive Characters from a String in Kotlin Android

Recently I can across to the problem when I have to remove consecutive characters from a String in Kotlin. My requirement was to allow a maximum of 2 same characters. For this purpose, I have written a generic method to Remove extra same repeating and duplicate Characters from a String in Kotlin.

Following is the Kotlin code if you are looking for Java code, you can find it here.

Just copy and pass the following 2 utility methods in your project and it will work for you. This removeConsecutiveCharactersInString(...) method takes 2 parameters, a String and a count of max allowed the same characters. Then it returns the resulting string by removing extra duplicate characters. For example, if we pass the String “abccccdddaf” and count 2. It will return “abccddaf” as the response.

Method to Remove Consecutive Characters from a String in Kotlin

fun removeConsecutiveCharactersInString(str: String, maxConsecutiveAllowedCount: Int): String {
    val builder = StringBuilder(str)
    var i = 0
    while (i < builder.length) {
        var foundCount = 0
        for (j in i - 1 downTo 0) {
            if (lowerCasedChar(builder[i]) == lowerCasedChar(builder[j])) {
                foundCount++
                if (foundCount >= maxConsecutiveAllowedCount) {
                    builder.deleteCharAt(i)
                    i--
                    break
                }
            } else {
                break
            }
        }
        i++
    }
    return builder.toString()
}

private fun lowerCasedChar(ch: Char): Char {
    val intChar = ch.toInt()
    return if (intChar >= 65 && intChar <= 90) {
        (intChar + 32).toChar()
    } else ch
}

You can call this method in the following way

removeConsecutiveCharactersInString("abccccdddaf", 2);

How does it work?

As you can see in the code, first we convert the String object into StringBuilder, for memory optimization during the iterations. Then we have implemented 2 nested loops, and we check previous characters for each until we found a different character. If we find consecutive characters more than the count, we remove it. The second lowerCasedChar(...) method is written to convert uppercase characters into lowercase. And this method is called in the first method.

That’s it. Enjoy 🙂

You can also find other useful helping materials and tutorials in our Coding Articles & Tutorials Knowledge Base.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

One thought on “Method to Remove Consecutive Characters from a String in Kotlin Android

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: