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,683 questions

55,435 answers

573 users

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

1 Answer

0 votes
import scala.collection.mutable
import scala.util.matching.Regex

object WordDeduplicator:

  /** 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 string containing text and punctuation.
    * @return Space-separated unique words.
    */
  def removeDuplicateWords(input: String): String =
    if input == null || input.trim.isEmpty then return ""

    // 1. Regex pattern using Unicode property escapes:
    //    \p{L} matches any Unicode letter, \p{N} matches numbers.
    val wordRegex: Regex = """[\p{L}\p{N}_]+""".r

    // 2. Mutable Set for O(1) case-insensitive duplicate tracking
    val seenWords = mutable.HashSet[String]()

    // 3. Extract word strings and filter sequentially
    val uniqueWords = wordRegex
      .findAllIn(input)
      .filter { word =>
        val lower = word.toLowerCase
        // HashSet.add returns true if the element was NOT present
        seenWords.add(lower)
      }
      .toList

    // 4. Join unique words with a single space
    uniqueWords.mkString(" ")

  def main(args: Array[String]): Unit =
    val input = "Hello! こんにちは,  ,hello こんにちは Bună ziua; Γεια σας Bună ziua *HELLO* Γεια σας"
    
    val result = removeDuplicateWords(input)
    
    println(result)



/*
run:

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

*/

 



answered Aug 4 by avibootz

Related questions

...