如何在Scala中检查字符串是否为十进制数

Ple*_*exQ 52 scala

我仍然是Scala的新手,我几乎每天都在发现新的有趣的做事方式,但它们并不总是明智的,有时候已经存在于语言中作为一种结构而我只是不喜欢知道他们.所以,有了这个序言,我正在检查一个给定的字符串是否完全由数字组成,所以我在做:

def isAllDigits(x: String) = x.map(Character.isDigit(_)).reduce(_&&_)
Run Code Online (Sandbox Code Playgroud)

这是明智的还是不必要的愚蠢?有更好的方法吗?调用x.toInt并捕获异常更好,还是不那么惯用?是否存在性能优势/劣势?

Jes*_*per 90

试试这个:

def isAllDigits(x: String) = x forall Character.isDigit
Run Code Online (Sandbox Code Playgroud)

forall获取一个函数(在这种情况下Character.isDigit),该函数接受一个参数,该参数是集合元素的类型并返回一个Boolean; 它返回true如果函数返回true集合中的所有元素,并false以其他方式.

  • `isAllDigits("")`返回`true`.这段代码为空字符串返回`false`:`def isAllDigits(x:String)=(x!="")&&(x forall Character.isDigit)`. (6认同)

Rex*_*err 35

你想知道字符串是否是整数?然后.toInt它捕获异常.你想知道字符串是否都是数字?然后问一个:

s.forall(_.isDigit)
s matches """\d+"""
Run Code Online (Sandbox Code Playgroud)

  • @Ixx - `matches`需要完全匹配.还有其他方法将正则表达式绑定到例如第一次出现. (3认同)

Tva*_*roh 22

你也可以考虑这样的事情:

import scala.util.control.Exception.allCatch

def isLongNumber(s: String): Boolean = (allCatch opt s.toLong).isDefined
// or
def isDoubleNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 7

首先Scala 2.13我们可以使用String::toDoubleOption, 来确定字符串是否是十进制数:

\n\n
"324.56".toDoubleOption.isDefined // true\n"4.06e3".toDoubleOption.isDefined // true\n"9w01.1".toDoubleOption.isDefined // false\n
Run Code Online (Sandbox Code Playgroud)\n\n

确定 String 是否为简单 Int 的类似选项:

\n\n
"324".toIntOption.isDefined // true\n"\xc3\xa032".toIntOption.isDefined // false\n"024".toIntOption.isDefined // true\n
Run Code Online (Sandbox Code Playgroud)\n


dre*_*xin 5

你可以简单地使用正则表达式.

val onlyDigitsRegex = "^\\d+$".r

def isAllDigits(x: String) = x match {
  case onlyDigitsRegex() => true
  case _ => false
}
Run Code Online (Sandbox Code Playgroud)

或者干脆

def isAllDigits(x: String) = x.matches("^\\d+$")
Run Code Online (Sandbox Code Playgroud)

为了改善这一点,您可以使用pimp my library模式使其成为字符串上的方法:

implicit def AllDigits(x: String) = new { def isAllDigits = x.matches("^\\d+$") }

"12345".isAllDigits // => true
"12345foobar".isAllDigits // => false
Run Code Online (Sandbox Code Playgroud)


Yor*_*iev 5

import scala.util.Try


object NumCruncher {

  def isShort(aString: String): Boolean = Try(aString.toLong).isSuccess
  def isInt(aString: String): Boolean = Try(aString.toInt).isSuccess
  def isLong(aString: String): Boolean = Try(aString.toLong).isSuccess
  def isDouble(aString: String): Boolean = Try(aString.toDouble).isSuccess
  def isFloat(aString: String): Boolean = Try(aString.toFloat).isSuccess

  /**
   *
   * @param x the string to check
   * @return true if the parameter passed is a Java primitive number
   */
  def isNumber(x: String): Boolean = {
    List(isShort(x), isInt(x), isLong(x), isDouble(x), isFloat(x))
      .foldLeft(false)(_ || _)
  }

}
Run Code Online (Sandbox Code Playgroud)