LoginSignup
4
1

More than 3 years have passed since last update.

KotlinのChar型のtoInt()に引っかかった

Last updated at Posted at 2021-02-28

はじめに

Kotlinで文字列を数値に変換した際に詰まった時のメモ

問題発生の経緯

Kolinで文字列を数値に変換した際に発生

  • 該当のコード
fun main() {
    var input = readLine()?: throw Exception()
    for (n in input){
        println(n.toInt())
    }
}

123を標準入力で受け取る。

  • 想定標準出力
1
2
3

がしかし、
このコードで出力されるのは、以下である。

  • 実際の出力
49
50
51

!?!?!?!?!?!?!?!?!?!?

解決した方法

上記のコードでは、String型の値をfor式で回し配列として扱っているので(String型はCharSequence型でもある)、nに入っている値の型はChar型(String型ではない)になる。
また、公式ドキュメントによると、

fun toInt(): Int
Returns the value of this character as a Int.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-char/to-int.html

Char型のValueをInt型で返すとのこと。

解決法としては、Character.getNumericValue(char)を使うと、charの文字を数値に変換してくれる。

fun main() {
    var input = readLine()?: throw Exception()
    for (n in input){
        println(Character.getNumericValue(n))
    }
}

もしくは、Charのvalueから'0'(48)を引けばいい。

fun main() {
    var input = readLine()?: throw Exception()
    for (n in input){
        println(n.digitToInt())
    }
}
fun Char.digitToInt(): Int {
    if (this in '0'..'9') {
        return this - '0'
    }
    throw IllegalArgumentException("Char $this is not a decimal digit")
}

ちなみに、上記のコードはKotlin1.4以降でExperimentalで実装されている。

参考

4
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1