How to convert a number to a string collection
e.g.:
- If the number is 234, I would like the 开发者_运维问答result to be
List<String>
containing2,3,4
(3 elements) - If the number is 8763, I would like the result to be
List<String>
containing8,7,6,3
(4 elements)
Does commons-math already have such a function?
- Convert the number to a String (
123
becomes"123"
). UseInteger.toString
. - Convert the string to a char array (
"123"
becomes{'1', '2', '3'}
). UseString.toCharArray
. - Construct a new, empty
Vector<String>
(or some other List type). - 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
andList.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:
- Converts
num
to aString
usingString.valueOf(num)
- Splits the String by non-word boundaries, in this case, every letter boundary except the start and the finish, using
.split("\\B")
(this returns aString[]
) - Converts the
String[]
to aList<String>
usingArrays.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
精彩评论