1

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,";
koli
  • 194
  • 1
  • 6
  • 24
  • 1
    possible duplicate of [splitting a comma separated string](http://stackoverflow.com/questions/10631715/splitting-a-comma-separated-string) and [Java: How to convert comma separated String to ArrayList](http://stackoverflow.com/questions/7488643/java-how-to-convert-comma-separated-string-to-arraylist) – Paul Bellora Sep 18 '13 at 04:35

5 Answers5

6

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(",");
tskuzzy
  • 35,812
  • 14
  • 73
  • 140
4
String[] myArray = result.split(",");

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

Woodchuck
  • 3,869
  • 2
  • 39
  • 70
Kon
  • 10,702
  • 6
  • 41
  • 58
2

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can do like this :

String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
  • wat about first comma , ur codse w'll result into blank space for 1st index – Shakeeb Ayaz Sep 18 '13 at 06:15
  • @user123 I just gave an example how to use spilt function. – Vimal Bera Sep 18 '13 at 06:21
  • question is String result=",17,18,19," not String result="17,18,19," first char is comma, for asked question split(",") will give num[1]=17 and num[0]=blank space.question is about to truncating first comma also – Shakeeb Ayaz Sep 18 '13 at 06:31
1
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);
    }
rickygrimes
  • 2,637
  • 9
  • 46
  • 69