Sling Academy
Home/Kotlin/Removing Duplicate Characters in Strings in Kotlin

Removing Duplicate Characters in Strings in Kotlin

Last updated: December 05, 2024

Working with strings is a fundamental part of programming, and one common task you might encounter is removing duplicate characters from a string. In this article, we will explore how you can remove duplicate characters in a string using Kotlin, a modern programming language that is concise and expressive. Kotlin is designed to interoperate fully with Java, but it brings more clarity and ease of use.

Understanding the Problem

Consider a string that contains repetitive characters. For example, the string "banana" has duplicate characters 'a' and 'n'. The goal is to create a new string where all characters appear only once, maintaining their original order in the string.

Approach to the Solution

There are multiple ways to achieve this in Kotlin, leveraging its powerful standard library. We'll look at a few methods to achieve this task efficiently.

Method 1: Using a Set

A Set is a collection that does not allow duplicate elements. By leveraging this property, we can preserve the distinct characters of a string.


fun removeDuplicatesUsingSet(input: String): String {
    val resultSet = mutableSetOf<Char>()
    return input.filter { 
        resultSet.add(it) 
    }
}

fun main() {
    val original = "banana"
    val withoutDuplicates = removeDuplicatesUsingSet(original)
    println(withoutDuplicates)  // Outputs: "ban"
}

In this method, we traverse the string and add each character to a mutable set, which automatically handles duplicates. Then, filter is used to retain only those characters that are added to the set for the first time.

Method 2: Using Distinct

Kotlin's collections have a handy distinct extension function which can be used on sequences, lists, arrays, and more. It returns a list where each element appears only once.


fun removeDuplicatesUsingDistinct(input: String): String {
    return input.toList().distinct().joinToString("")
}

fun main() {
    val original = "developer"
    val withoutDuplicates = removeDuplicatesUsingDistinct(original)
    println(withoutDuplicates)  // Outputs: "developr"
}

This solution is succinct and takes advantage of Kotlin's expressive syntax to achieve our objective.

Method 3: Using StringBuilder

For better performance with large strings, consider using StringBuilder to construct your result, since it efficiently handles dynamic string concatenation.


fun removeDuplicatesUsingStringBuilder(input: String): String {
    val seen = mutableSetOf<Char>()
    val builder = StringBuilder()
    for (char in input) {
        if (seen.add(char)) {
            builder.append(char)
        }
    }
    return builder.toString()
}

fun main() {
    val original = "mississippi"
    val withoutDuplicates = removeDuplicatesUsingStringBuilder(original)
    println(withoutDuplicates)  // Outputs: "misp"
}

This method leverages both a MutableSet and StringBuilder, explicitly controlling the process of building up the result string while keeping track of seen characters.

Comparison of Methods

Each of these methods has its own use case and efficiency:

  • Using a Set: Very clear and direct, provides intermediate collections.
  • Using Distinct: Most concise and makes use of Kotlin's idiomatic collections operations.
  • StringBuilder: Best suited for performance concerns with very large strings.

In summary, removing duplicate characters in a string is a problem with many potential solutions in Kotlin. Depending on the requirements of your application or your personal preference, you might choose one method over another. The power and flexibility of Kotlin allow you to write expressive and efficient code, helping you manage tasks like these with ease.

Next Article: Padding Strings with Characters in Kotlin

Previous Article: Joining and Splitting Strings with Custom Delimiters in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin