Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,596 questions

55,330 answers

573 users

How to remove duplicate words with Unicode characters from free‑text in Kotlin

1 Answer

0 votes
/**
 * Removes duplicate words from a free-text string containing Unicode characters.
 * Preserves word order and the case of the first occurrence.
 *
 * @param input The input free-text string containing punctuation and Unicode words.
 * @return A space-separated string of unique words.
 */
fun removeDuplicateWords(input: String?): String {
    // Built-in Kotlin extension function checking for null, empty, or whitespace-only strings
    if (input.isNullOrBlank()) return ""

    // 1. \p{L} matches any Unicode letter, \p{N} matches digits.
    val wordRegex = Regex("""[\p{L}\p{N}_]+""")

    // 2. HashSet for O(1) duplicate tracking.
    val seenWords = HashSet<String>()

    // 3. Extract matches as a Sequence and keep first occurrence (case-insensitive).
    return wordRegex.findAll(input)
        .map { it.value }
        .filter { word ->
            // HashSet.add returns true if the element was NOT already in the set
            seenWords.add(word.lowercase())
        }
        .joinToString(" ")
}

fun main() {
    val input = "Hello! こんにちは,  ,hello こんにちは Bună ziua; Γεια σας Bună ziua *HELLO* Γεια σας"

    val result = removeDuplicateWords(input)

    println(result)
}



/*
run:

Hello こんにちは Bună ziua Γεια σας

*/

 



answered 3 days ago by avibootz

Related questions

...