someguy234
someguy234

Reputation: 559

Trouble splitting a string to an array

I am having trouble finding this exact question online so I thought to ask. Let's say I have a string "0123". I want to split this string to an array ['0','1','2','3'].

I know in (for example) Python you can easily do "0123".split() without any input, but in Java the method requires an input and even if I put empty string such as .split("") it doesn't work.

What am I missing?

Upvotes: 2

Views: 100

Answers (4)

Nathan
Nathan

Reputation: 2103

You can use a regex with the String.split(String regex) method:

String[] characters = "0123".split("|");

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

You can get it as a char[] by using String.toCharArray() -

char[] chars = str.toCharArray();

Or, you could get is as a String[] by using String.split(String) like,

String str = "0123";
char[] chars = str.toCharArray();
System.out.println(Arrays.toString(chars));
String[] strings = str.split("");
System.out.println(Arrays.toString(strings));

Output is

[0, 1, 2, 3]
[0, 1, 2, 3]

Upvotes: 0

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9872

Use toCharArray(); - for example:

char c[]= "0123".toCharArray();

this is exactly same to

char c[]={'0','1','2','3'} ;

Upvotes: 4

Keith Enlow
Keith Enlow

Reputation: 914

You can still use .split() and use a regular expression to catch every digit or character like:

string.split("\\d");

Upvotes: 0

Related Questions