There is an input string:
String str="(1,6),(2,5),(7,10),(12,20)";
How to split the string so that an integer array containing only the integers is obtained?
i.e the output array should be: arr={1,6,2,5,7,10,12,20};
There is an input string:
String str="(1,6),(2,5),(7,10),(12,20)";
How to split the string so that an integer array containing only the integers is obtained?
i.e the output array should be: arr={1,6,2,5,7,10,12,20};
You could use regex like this :
public static void main(String args[]) {
String s = "(1,6),(2,5),(7,10),(12,20)";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
List<Integer> li = new ArrayList<Integer>();
while (m.find()) {
System.out.println(m.group());
li.add(Integer.parseInt(m.group()));
}
// convert li to array here if you want.
}
O/P :
1
6
2
5
7
10
12
20
How about:
str.replaceAll("\\(|\\)","").split(",");
Simply split by \D+.
You need to escape the backslash since in a string literal: .split("\\D+").
You'll have empty values, don't forget to handle them ;)
The approach is to remove all parentheses and then split by commas.
String str="(1,6),(2,5),(7,10),(12,20)";
//convert to string array of numbers
String[] numbersStr = str.replaceAll("\\(","").replaceAll("\\)","").split(",");
//convert to int array of numbers
int[] numbers = new int[numbersStr.length];
for(int i = 0; i < numbersStr.length; ++i)
numbers[i] = Integer.parseInt(numbersStr[i]);
Note that this is valid if you have ONLY parentheses and commas in your string, else you'll need to replace other characters with empty string before split.
Inspired by this answer and this answer.