Jason
Jason

Reputation: 12789

How to convert a number to a string collection

e.g.:

Does commons-math already have such a function?

Upvotes: 0

Views: 504

Answers (5)

Miserable Variable
Miserable Variable

Reputation: 28761

This seems like homework.

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

Upvotes: 0

Mark Elliot
Mark Elliot

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:

  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...)

Upvotes: 2

wjans
wjans

Reputation: 10115

Try this:

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

It will create list of Strings:

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

Upvotes: 0

mgiuca
mgiuca

Reputation: 21377

  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.

Upvotes: 6

Jesse Barnum
Jesse Barnum

Reputation: 6856

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

Upvotes: 0

Related Questions