I have a input string like
{{1,2},{3,4},{5,6}}.
I want to read the numbers into an two dimensional array like
int[][] arr = {{1,2},{3,4},{5,6}}.
Is there a good way to convert this string
into int[][]
? Thanks.
I have a input string like
{{1,2},{3,4},{5,6}}.
I want to read the numbers into an two dimensional array like
int[][] arr = {{1,2},{3,4},{5,6}}.
Is there a good way to convert this string
into int[][]
? Thanks.
The basic idea is as follows, you will have to add error handling code and more logical calculation of array size yourself. I just wanted to display how to split the string and make int [][]array
.
String test = "{{1,2},{3,4},{5,6}}";
test = test.replace("{", "");
test = test.replace("}", "");
String []nums = test.split(",");
int numIter = 0;
int outerlength = nums.length/2;
int [][]array = new int[outerlength][];
for(int i=0; i<outerlength; i++){
array[i] = new int[2];
for(int j=0;j<2;j++){
array[i][j] = Integer.parseInt(nums[numIter++]);
}
}
hope it helps!
I'd go for solution using dynamic storage such as List from Collections, and then convert this to fixed primitive array at the end.
public static void main(String[] args) throws Exception {
System.out.println(Arrays.deepToString(parse("{{1,2},{3,4},{5,6}}")));
}
private static int[][] parse(String input) {
List<List<Integer>> output = new ArrayList<>();
List<Integer> destination = null;
Pattern pattern = Pattern.compile("[0-9]+|\\{|\\}");
Matcher matcher = pattern.matcher(input);
int level = 0;
while (matcher.find()) {
String token = matcher.group();
if ("{".equals(token)) {
if (level == 1) {
destination = new ArrayList<Integer>();
output.add(destination);
}
level++;
} else if ("}".equals(token)) {
level--;
} else {
destination.add(Integer.parseInt(token));
}
}
int[][] array = new int[output.size()][];
for (int i = 0; i < output.size(); i++) {
List<Integer> each = output.get(i);
array[i] = new int[each.size()];
for (int k = 0; k < each.size(); k++) {
array[i][k] = each.get(k);
}
}
return array;
}
Another alternative would be translate {
to [
and }
to ]
, then you have JSON, just use your favourite JSON parser, here I used GSON.
private static int[][] parse(String string) {
JsonElement element = new JsonParser().parse(string.replace("{", "[").replace("}", "]"));
JsonArray obj = element.getAsJsonArray();
int [][] output = new int[obj.size()][];
for (int i = 0; i < obj.size(); i++) {
JsonArray each = obj.get(i).getAsJsonArray();
output[i] = new int[each.size()];
for (int k = 0; k < each.size(); k++) {
output[i][k] = each.get(k).getAsInt();
}
}
return output;
}