How to get the separate digits of an int number?

前端 未结 30 2325
陌清茗
陌清茗 2020-11-22 03:03

I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.

How can I get

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:11

    I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:

    int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();
    

    To be clear: You use String.valueOf(number) to convert int to String, then chars() method to get an IntStream (each char from your string is now an Ascii number), then you need to run map() method to get a numeric values of the Ascii number. At the end you use toArray() method to change your stream into an int[] array.

提交回复
热议问题