Reputation: 12789
e.g.:
List<String>
containing 2,3,4
(3 elements)List<String>
containing 8,7,6,3
(4 elements)Does commons-math already have such a function?
Upvotes: 0
Views: 504
Reputation: 28761
This seems like homework.
Consider using %
and /
to get each digit instead of converting the entire number to a String
Upvotes: 0
Reputation: 77104
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:
num
to a String
using String.valueOf(num)
.split("\\B")
(this returns a String[]
)String[]
to a List<String>
using Arrays.asList(T...)
Upvotes: 2
Reputation: 10115
Try this:
Arrays.asList(String.valueOf(1234).split("(?!^)"))
It will create list of Strings:
["1", "2", "3", "4"]
Upvotes: 0
Reputation: 21377
123
becomes "123"
). Use Integer.toString
."123"
becomes {'1', '2', '3'}
). Use String.toCharArray
.Vector<String>
(or some other List type).{'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.
Upvotes: 6