0

I'm trying to do something like this:

Input: a string like (the numbers are random):

"<12, 3>, <4, 5>, <23, 5>, <33, 56>" 

Output: an array of integers like this one

[12, 3, 4, 5, 23, 5, 33, 56]

I tried using some grammars and some splits but I'm always ending with string or chars.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156

2 Answers2

0

This should do what you want to do:

package split;

public class Main {

    public static void main(String[] args){

        String mString = "<12,3>,<4,5>,<23,5>,<33,56>"; 
        mString = mString.replace("<", ""); 
        mString = mString.replace(">", ""); 
        String[] stringArray = mString.split(","); 

        int[] intArray = new int[stringArray.length];
        int index = 0; 
        for(String mS : stringArray){
            intArray[index] = Integer.parseInt(mS); 
            index++;
        }

        for(int i : intArray){
            System.out.println(i); 
        }
    }
}

To change a String to an int you use Integer.parseIn("your String");.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
0

Sometimes the trick with regular expressions is not to try to match the complete format of the thing you are trying to parse, but instead just to find the things you are looking for.

In your case, since you want to flatten the list of numbers, all you need to look for is a sequence of numbers. So that is easy to do.

List<Integer> findNumbers(String s) {
    List<Integer> result = new ArrayList<Integer>();
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        result.add(Integer.parseInt(matcher.group()));
    }
    return result;
}
Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88