Following is the algorithm to parse Int from a String :
- Trim the input to remove leading and trailing spaces
- If the input is empty, return null
- Declare a
num
variable to store the parsed Int and initialize it to 0 - For each character in string :
- if it is digit, parse it and update
num
asnum * 10 + digit
- else (non digit character), return
null
- if it is digit, parse it and update
- return
num
Example
Example
Input = " 123 " = "123"
num = 0
'1' -> num = num * 10 + 1 = 0*10 + 1 = 0 + 1 = 1
'2' -> num = num * 10 + 2 = 1*10 + 2 = 10 + 2 = 12
'3' -> num = num * 10 + 3 = 12*10 + 3 = 120 + 3 = 123
num = 123
Implementation
Implementation
fun String.toIntOrNull(): Int? {
// Trim the input
val input = trim()
// Empty input
if (input.isEmpty()) return null
// Create the number
var num = 0
// Parse each digit
input.forEach { c ->
if (c in '0'..'9') {
val digit = c.code - '0'.code
num = (num * 10) + digit
} else {
return null
}
}
return num
}