Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串的Scala if条件给出了不同的结果_Scala - Fatal编程技术网

字符串的Scala if条件给出了不同的结果

字符串的Scala if条件给出了不同的结果,scala,Scala,vc100_60大于vc75_60 如何在scala代码中实现它 scala> val str1 ="vc100_60" str1: String = vc100_60 scala> val str2 ="vc75_60" str2: String = vc75_60 scala> val result = if(str1 > str2) { println(str1) } else {println(str2)} vc75_60 预期答案为vc100_

vc100_60大于vc75_60

如何在scala代码中实现它

 scala> val str1 ="vc100_60"
 str1: String = vc100_60

 scala> val str2 ="vc75_60"
 str2: String = vc75_60

 scala> val result = if(str1 > str2) { println(str1) } else {println(str2)}
 vc75_60
预期答案为vc100_60 但我得到了vc75_60


要从if条件中获得vc100_60,需要做哪些代码更改这是一个词典比较。它们是按位置进行比较的。在这种情况下,
“99”
将大于
“1000”
,因为
“99”
中的第一个字符较大。每当一个字符变大时,就不会比较其他字符。

有很多方法可以将这些字符串解析为您感兴趣的整数值进行比较-下面是一个使用正则表达式的方法:

val regex = """vc(\d+)_.*""".r

def parse(str: String): Int = str match {
  case regex(v) => v.toInt
  case _ => 0 // when parsing fails; Alternatively - throw exception or use a different default value
}

if (parse(str1) > parse(str2)) { println(str1) } else { println(str2) }

// or, another way to print the minimum 
// which can easily be applied to more than two strings:
val min = List(str1, str2).minBy(parse)
println(min)

当然,我根据这两个例子对格式做了一些假设,如果必要的话修复正则表达式

字符串按字典顺序进行比较,因此
vc100_60
vc75_60,因为
1
7
;你的意思是你知道输入格式,只想比较
vc
之间的数字部分吗?是的,我想我需要对int和比较应用split和substring以及cast