HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaModerate

Method to convert String to int array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodconvertarrayintstring

Problem

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 helper = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i  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;
}

Solution

Ohhhh.... XOR logic on booleans in Java ..... how esoteric:

if (s.charAt(i) == ' ' ^ i == s.length() - 1) {


That should be removed "just because". It's hard to understand, the logic is inverted, and it is not short-circuit, so it tests the i == s.length() - 1 even when s.charAt(i) == ' '

I think what you have is an inverted logic problem. You are looking for all the digits in the input, when, instead, you should be looking for not-digits....

The supporting logic, using StringBuilders, etc. is not a bad idea.... but, have you considered a regular-expression?

String[] digitwords = input.split("\\D+");
int[] result = new int[digitwords.length];
for (int i = 0; i < result.length; i++) {
    result[i] = Integer.parseInt(digitwords[i]);
}
return result;


The split there, is "split on all sequences that do not contain digits"

Java8 may help (with an added filter to remove empty values, not in the loop above), with:

return Arrays.stream(input.split("\\D+"))
       .filter(word -> !word.isEmpty())
       .mapToInt(Integer::parseInt)
       .toArray();

Code Snippets

if (s.charAt(i) == ' ' ^ i == s.length() - 1) {
String[] digitwords = input.split("\\D+");
int[] result = new int[digitwords.length];
for (int i = 0; i < result.length; i++) {
    result[i] = Integer.parseInt(digitwords[i]);
}
return result;
return Arrays.stream(input.split("\\D+"))
       .filter(word -> !word.isEmpty())
       .mapToInt(Integer::parseInt)
       .toArray();

Context

StackExchange Code Review Q#75865, answer score: 10

Revisions (0)

No revisions yet.