skip to Main Content

Not sure how to explain this the best but I have a variable with 4 int’s in it. Is there a simple way to extract the 4 int’s into 4 seperate var’s?

Example:
The variable contains: 4567

And then the output is:

   var1 = 4 
   var2 = 5
   var3 = 6
   var4 = 7

2

Answers


  1. You can do this:

    val input = 4567
    
    val var1 = input / 1000
    val var2 = (input % 1000) / 100
    val var3 = (input % 100) / 10
    val var4 = (input % 10)
    
    Login or Signup to reply.
  2. Another way can be:

    val n = 4567
    val (var1, var2, var3, var4) = "$n".map { it.digitToInt() }
    

    Note that this will fail if number contains less than 4 digits.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search