views:

37

answers:

2

Hi,

I have a String looks like this

String read = "1130:5813|1293:5803|1300:5755|1187:5731|"

As you can see that there are 4 pair of integer values are there.

i want to add there values into the list something like this

a = 1130
b = 5813

groupIt pair = new groupIt(a,b);
List<groupIt> group  = new ArrayList<groupIt>();
group.add(pair);

How can i do this for the 4 pair of String. You can use pattern.compile() -- stuff

As you know its Java.

thanks

+3  A: 

Why won't you use

String[] tokens = read.split("\\|");
for (String token : tokens) {
   String[] params = token.split(":");
   Integer a = Integer.parseInt(params[0]);
   Integer b = Integer.parseInt(params[1]);

   // ...

}
mgamer
params should be a String[]. And you might have to escape the |, as split accepts a regexp.
gpeche
@gpeche You are absolutely right. I've just amended my response.
mgamer
Yes i can do that too. Thanks for the help.. it works.Actually i was trying with patterns.. But this works.
salman
I strongly suggest looking at google guava and its `Splitter` - it is much more likely to do what you expect from a split-method and is fast. Plus, I love google and their fluent interfaces... :)
LeChe
A: 

Just for good measure, here is your regex:

public class RegexClass {
    private static final Pattern PATTERN = Pattern.compile("(\\d{4}):(\\d{4})\\|");

    public void parse() {
        String text = "1130:5813|1293:5803|1300:5755|1187:5731|";
        Matcher matcher = PATTERN.matcher(text);
        int one = 0;
        int two = 0;
        while(matcher.find()) {
           one = Integer.parseInt(matcher.group(1));
           two = Integer.parseInt(matcher.group(2));

           // Do something with them here
        }
    }
}

However, I do think that Michael is correct: his solution is better!

Good luck...

LeChe