koli
koli

Reputation: 204

How to put Java String to array

I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?

String result=",17,18,19,";

Upvotes: 1

Views: 35474

Answers (5)

Kon
Kon

Reputation: 10810

String[] myArray = result.split(",");

This returns an array separated by your argument value, which can be a regular expression.

Upvotes: 4

rickygrimes
rickygrimes

Reputation: 2716

String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
    for(String resultArr:resultArray)
    {
        System.out.println(resultArr);
    }

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Try split()

Assuming this as a fixed format,

String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
    System.out.println(string);
}

//output : 17 18 19

That split() method returns

the array of strings computed by splitting this string around matches of the given regular expression

Upvotes: 2

tskuzzy
tskuzzy

Reputation: 36456

First remove leading commas:

result = result.replaceFirst("^,", "");

If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailing empty elements):

String[] arr = result.split(",");

One liner:

String[] arr = result.replaceFirst("^,", "").split(",");

Upvotes: 6

Vimal Bera
Vimal Bera

Reputation: 10497

You can do like this :

String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..

Upvotes: 1

Related Questions