I was working on a suggestion for this question, but the method, I would've suggested the OP do something similar to, seems a bit convoluted.
It's supposed to take a String input and return an array of only the integers deliminated by spaces. It does this correctly, but It feels like I may be doing some unnecessary things or there's a more succinct way to do this, such as with regex.
public static int[] getIntegers(String s) {
int[] result;
ArrayList<Integer> helper = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ' ^ i == s.length() - 1) {
if (i == s.length() - 1) { sb.append(s.charAt(i)); }
if (sb.toString().length() > 0) {
try { helper.add(Integer.parseInt(sb.toString()));
} catch(NumberFormatException nfe) {
// Ignore non-integers
}
sb.setLength(0);
continue;
}
}
sb.append(s.charAt(i));
}
result = new int[helper.size()];
int i = 0;
for (Integer n : helper) {
result[i++] = n;
}
return result;
}
rags-to-riches
too? Not sure the extent of the makeover here. :D \$\endgroup\$