【问题标题】:How do I convert a digit Char (0-9) to its numeric value? [duplicate]如何将数字 Char (0-9) 转换为其数值? [复制]
【发布时间】:2017-12-08 11:35:47
【问题描述】:

Char.toInt() 返回字符的 ASCII 码,而不是其数值。那么如何将 Char 转换为具有正确数值的整数呢?

【问题讨论】:

标签: kotlin


【解决方案1】:

答案:

您可以在 Char 类上创建一个扩展,该扩展从 toInt() 返回的 ASCII 代码中减去 48。这将为您提供正确的字符数值!

fun Char.getNumericValue(): Int {
    if (this !in '0'..'9') {
        throw NumberFormatException()
    }
    return this.toInt() - '0'.toInt()
}

【讨论】:

  • 这在技术上是不正确的,因为isDigit 将返回true 用于不一定是0-9 的字符。 ١,字符 'ARABIC-INDIC DIGIT ONE' (U+0661)是一个数字,但 toInt() - 48 将返回 1585。您可能想改用this in '0'..'9'
  • 谢谢,根据您的反馈更新了答案。
【解决方案2】:

您也可以将其转换为String,然后使用toInt(),这可能更明显。

fun Char.getNumericValue(): Int {
    if (!isDigit()) {
        throw NumberFormatException()
    }
    return this.toString().toInt()
}

【讨论】:

  • 确实如此,但我怀疑如果我需要大量运行该操作,效率会降低吗?如果我错了,请纠正我!
猜你喜欢
  • 2020-07-08
  • 1970-01-01
  • 2020-02-06
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 2019-09-01
  • 2011-08-10
相关资源
最近更新 更多