Removing multiple character types from a string

前端 未结 2 951
攒了一身酷
攒了一身酷 2020-12-30 03:39

Is this an acceptable approach for removing multiple character types from a string or is there a better (more efficient way)? The \"ilr\".contains(_) bit feels

相关标签:
2条回答
  • 2020-12-30 04:01

    I'd just use Java's good old replaceAll (it takes a regexp):

    "Twinkle twinkle little star, oh I wander what you are" replaceAll ("[ilr]", "")
    // res0: String = Twnke twnke tte sta, oh I wande what you ae
    

    In contrast to working with chars (as in filtering a Seq[Char]), using regular expressions should be Unicode-safe even if you're working with code points outside the basic multilingual plane. "There Ain't No Such Thing As Plain Text."

    0 讨论(0)
  • 2020-12-30 04:10

    There would be no significant difference, since there is only 3 characters to remove and no so big string to filter, but you may consider to use Set for this purpose. E.g.

    val toRemove = "ilr".toSet
    val words = sentence.filterNot(toRemove)
    
    0 讨论(0)
提交回复
热议问题