Klausos Klausos
Klausos Klausos

Reputation: 16060

Comma separators in a string of digits

There is a string data:

{4,15,26,7}

Comma separator is used to separate digits.

this.points=new ArrayList<Integer>();
    for (int i = 0; i < data.length(); i++) {
            this.points.add(Character.getNumericValue(data.charAt(i)));
    }

How to modify this code to be able to skip comma separators and save only digits in this.points?

Upvotes: 0

Views: 145

Answers (2)

WereWolfBoy
WereWolfBoy

Reputation: 508

It isn't that hard. Here are my sources: http://javarevisited.blogspot.nl/2011/09/string-split-example-in-java-tutorial.html

Determine if a String is an Integer in Java

So what you would want to do is this:

points = new ArrayList<Integer>;
String foo = "4,15,10,100";
String[] splits = foo.split(",");

for(String temp : splits){
if(Character.digit(temp)) points.add(Integer.parseInt(temp);
}

Upvotes: 0

Pragnani
Pragnani

Reputation: 20155

Try this,

String data="{4,15,26,7}";
data=data.substring(1,data.length-1);
String[] digits=data.split(",");
his.points=new ArrayList<Integer>();
    for (int i = 0; i < digits.length; i++) {
            this.points.add(Integer.parseInt(digits[i]));
    }

Upvotes: 5

Related Questions