从字符串数组中提取数字 [英] Extract numbers from String Array
问题描述
我有一个字符串数组
scala> tokens
res34: Array[String] = Array(The, value, of, your, profile, is, 234.2., You, have, potential, to, gain, 8.3, more.)
这里每个逗号分隔值都是一个字符串.
我想从中提取数字,即我的输出应该是 result = (234.2, 8.3) &它应该是可变的,以便我可以从另一个数组中读取并附加值
Here each of comma separated value is a String.
I want to extract numbers from this i.e. my output should be result = (234.2, 8.3) & it should be mutable so that I can read from another array and append values
我应该使用什么数据结构来实现这一点?
What data structure should I use to achieve this?
推荐答案
考虑
import scala.util._
tokens.flatMap(s => Try( s.split("\\W+").mkString(".").toDouble ).toOption)
我们将每个数组字符串进一步标记为单词,并在它们后面加上一个点(这应该去掉例如尾随的点);我们尽可能将结果标记转换为双精度值(注意 Try
toOption
会为失败的转换提供 None
).使用 flatMap
我们只保留成功的转换.
where we tokenize further each array string into words and append them by a dot (this ought to strip out for instance trailing dots); we convert the resulting tokens into doubles whenever possible (note Try
toOption
will deliver None
for failed conversions). With flatMap
we keep only successful conversion.
这篇关于从字符串数组中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!