G
Gerald Rosenberg
Given a variable string of the form assigned to myContent, is there a
different/better approach to converting the string a 2D int array?
I know I can move the Patterns out and make them static as an
performance improvement. Having to handle the bounds checking and
allocation of arrays always seems cumbersome. I do have to return an
int[][] and am *almost* assured that 9x9 will be large enough. Can you
suggest the best clean way of doing the checking and allocation?
Thanks,
Gerald
public int[][] runTest() {
int[][] x = new int[9][9];
String myContent = "{{1, 3}{26 ,04,35, 99 } { 87, 438,19}}";
Pattern pattern =
Pattern.compile("\\{+(\\s*\\d+)(\\s*\\,+\\s*\\d+\\s*)+\\}+");
Pattern subpattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(myContent);
int I = 0;
int j = 0;
while (matcher.find()) {
Matcher submatcher = subpattern.matcher(matcher.group());
while (submatcher.find()) {
x[j] = new Integer(submatcher.group()).intValue();
System.err.println(I + ":" + j + " = " + x[j]);
j++;
}
I++;
}
return x;
}
Output:
0:0 = 1
0:1 = 3
1:2 = 26
1:3 = 4
1:4 = 35
1:5 = 99
2:6 = 87
2:7 = 438
2:8 = 19
different/better approach to converting the string a 2D int array?
I know I can move the Patterns out and make them static as an
performance improvement. Having to handle the bounds checking and
allocation of arrays always seems cumbersome. I do have to return an
int[][] and am *almost* assured that 9x9 will be large enough. Can you
suggest the best clean way of doing the checking and allocation?
Thanks,
Gerald
public int[][] runTest() {
int[][] x = new int[9][9];
String myContent = "{{1, 3}{26 ,04,35, 99 } { 87, 438,19}}";
Pattern pattern =
Pattern.compile("\\{+(\\s*\\d+)(\\s*\\,+\\s*\\d+\\s*)+\\}+");
Pattern subpattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(myContent);
int I = 0;
int j = 0;
while (matcher.find()) {
Matcher submatcher = subpattern.matcher(matcher.group());
while (submatcher.find()) {
x[j] = new Integer(submatcher.group()).intValue();
System.err.println(I + ":" + j + " = " + x[j]);
j++;
}
I++;
}
return x;
}
Output:
0:0 = 1
0:1 = 3
1:2 = 26
1:3 = 4
1:4 = 35
1:5 = 99
2:6 = 87
2:7 = 438
2:8 = 19