How to take the last vowel and any words after it of a string in Scala?

问题: Given the following Map("DIAMOND" -> "DAYMAHND", "THOUSAND" -> "THAWZAHND"), I want to take the value of each item in the current map and update those values in a new...

问题:

Given the following Map("DIAMOND" -> "DAYMAHND", "THOUSAND" -> "THAWZAHND"), I want to take the value of each item in the current map and update those values in a new map with the last vowel and every other word after it as values and the same word as keys. How would I do this in Scala? I heard of people accomplishing this by using .stripSuffix(). (Maps are immutable)

Input: Map("DIAMOND" -> "DAYMAHND", "THOUSAND" -> "THAWZAHND")

Output: Map("DIAMOND" -> "AHND", "THOUSAND" -> "AHND")

My Attempt:

val table1 = Map("DIAMOND" -> "DAYMAHND", "THOUSAND" -> "THAWZAHND")
val table2 = table1.map { case (key, value) =>
                            val string_2 = value
                                        .reverse
                                        .takeWhile("AEIOU".indexOf(_) == 
                                 -1)
                                (key, string_2 + value.charAt(value.length 
                                - 1 - string_2.length))
                                 }
                                .toMap

回答1:

table1.mapValues(w => w.drop(w.lastIndexWhere("AEIOU".contains(_))))

回答2:

A regular expression is probably the best approach. This is the simplest way to do it

table1.mapValues(_.split("(?=[AEIUO])").last)

However mapValues will re-compute this expression each time you read the map, so if you will use the map multiple times, do this:

table1.map{case (k, v) => k -> v.split("(?=[AEIUO])").last}
  • 发表于 2019-02-15 18:19
  • 阅读 ( 155 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除