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,";
1

5 Answers 5

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(",");
Sign up to request clarification or add additional context in comments.

3 Comments

@PaulVargas: No, this is Java
The calls to replaceFirst have unnecessary '/'s in the pattern and are missing a replacement string.
tskuzzy your answer is exactly correct. When i used other methods the length of the array is not properly out put. Thanks.
4
String[] myArray = result.split(",");

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

Comments

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

1 Comment

wat about first comma , ur codse w'll result into blank space for 1st index
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..

3 Comments

wat about first comma , ur codse w'll result into blank space for 1st index
@user123 I just gave an example how to use spilt function.
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
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);
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.