Converting Characters of a string containing only numbers to Int was a Kotlin task I recently faced.
Coding a for loop to iterate over the characters of a string was quickly done.
I browsed quickly through text funs and thought toInt can do the trick.
Well, not really 😉
Reading the toInt documentation also did not help in the first place unfortunately: Parses the string as an Int number and returns the result.
Reading about ascii printable characters did help me to solve the task:
The fun toInt returns different results if performed on top of a string or a character:
$ kotlinc >>> "2".toInt() 2 >>> '2'.toInt() 50
My case was about Characters. One solution is to subtract 48 in order to retrieve the expected 2 as Int for the Character ‘2’ .
The gist below contains several approaches to achieve this. The String someText contains not only numbers for testing purposes.
fun main(args: Array) { val someText = "ABC1234567890" for (i in (0 .. (someText.length-1))){ println(" number[$i]: ${someText[i]}") println("(number[$i] is Char): ${(someText[i] is Char)}") /* toInt return ascii dev code of a Character, _not_ the Character as Int in case of numbers */ println(" number[$i].toInt(): ${someText[i].toInt()}") println(" number[$i].toString().toIntOrNull(): " + "${someText[i].toString().toIntOrNull()}") /* ascii to Int : 48 is ascii code for '0' */ println(" number[$i].toInt() - 48: ${someText[i].toInt() - 48}") /* subtracts character zero ('0') thats ascii dec code is 48 */ println(" number[$i] - '0': ${someText[i] - '0'}") println("-----") } }
Conclusion
When converting Text to Int in Kotlin be aware of:
-
- ascii standard and the ascii decimal code 48 of ‘0’ (zero)
Leave a Reply