1

I have a string input which looks like this:

String equation = "(5.5 + 65) - 33".  

How would I go about separating these elements into an array which looked like this:

String array = {"(", "5.5", "+", "65", ")", "-", "33"}

I tried using the string split() method but because of there being no spaces between the parenthesis and the next digit it produces the incorrect format of:

String array = {"(5.5", "+"
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Sam091
  • 51
  • 4

1 Answers1

0

You can do this with a StreamTokenizer:

StreamTokenizer st = new StreamTokenizer(new StringReader(equation));
st.parseNumbers();

List<String> tokens = new ArrayList<>();
while (st.nextToken() != StreamTokenizer.TT_EOF) {
    switch (st.ttype) {
        case StreamTokenizer.TT_EOL:
            // ignore
            break;
        case StreamTokenizer.TT_WORD:
            tokens.add(st.sval);
            break;
        case StreamTokenizer.TT_NUMBER:
            tokens.add(String.valueOf(st.nval));
            break;
        default:
            tokens.add(String.valueOf((char) st.ttype));
    }
}
String[] array = tokens.toArray(new String[tokens.size()]);

Note that because this parses the numbers as double, they become e.g. 65.0 when converted back to strings. If you don't want that, you'll need to add some number formatting.

I suspect that whatever you're planning to do with them later, you actually want them as numbers though.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207