开发者

How to convert a number to a string collection

开发者 https://www.devze.com 2023-03-18 17:10 出处:网络
e.g.: If the number is 234, I would like the 开发者_运维问答result to be List<String> containing 2,3,4 (3 elements)

e.g.:

  • If the number is 234, I would like the 开发者_运维问答result to be List<String> containing 2,3,4 (3 elements)
  • If the number is 8763, I would like the result to be List<String> containing 8,7,6,3 (4 elements)

Does commons-math already have such a function?


  1. Convert the number to a String (123 becomes "123"). Use Integer.toString.
  2. Convert the string to a char array ("123" becomes {'1', '2', '3'}). Use String.toCharArray.
  3. Construct a new, empty Vector<String> (or some other List type).
  4. Convert each char in the char array to a String and push it onto the Vector ({'1', '2', '3'} becomes a Vector with "1", "2" and "3"). Use a for loop, Character.toString and List.add.

Edit: You can't use the Vector constructor; have to do it manually.

int num = 123;
char[] chars = Integer.toString(num).toCharArray();
List<String> parts = new Vector<String>();
for (char c : chars)
{
    parts.add(Character.toString(c));
}

There isn't an easier way to do this because it really isn't a very obvious or common thing to want to do. For one thing, why do you need a List of Strings? Can you just have a list of Characters? That would eliminate step 3. Secondly, does it have to be a List or can it just be an array? That would eliminate step 4.


You can use the built in java.util.Arrays.asList:

int num = 234;
List<String> parts = Arrays.asList(String.valueOf(num).split("\\B"));

Step by step this:

  1. Converts num to a String using String.valueOf(num)
  2. Splits the String by non-word boundaries, in this case, every letter boundary except the start and the finish, using .split("\\B") (this returns a String[])
  3. Converts the String[] to a List<String> using Arrays.asList(T...)


Arrays.asList( String.valueOf(number).toCharArray() )


Try this:

Arrays.asList(String.valueOf(1234).split("(?!^)"))

It will create list of Strings:

["1", "2", "3", "4"]


This seems like homework.

Consider using % and / to get each digit instead of converting the entire number to a String

0

精彩评论

暂无评论...
验证码 换一张
取 消