Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting up an equation using an ArrayList

If I enter an equation like:

9+3*2/1

My output is:

[9,3,2,1] 
[,+,*,/]

Why does my second array start off with a "," and how do I get rid of it so the output would be

[+,*,/]
String evaluate(String exp) {

        String setExpression = expr.getText();

        String[] numbers = setExpression.split("[*/+-]");
        String[] ops = setExpression.split("[123456789]");

        ArrayList <String> setNumbers = new ArrayList <String>();
        ArrayList <String> setOps = new ArrayList <String>();


        for(int i=0; i<numbers.length; i++){
            setNumbers.add(numbers[i]);
        }

        for(int i=0; i<numbers.length; i++){
            setOps.add(ops[i]);
        }

        System.out.println(setNumbers);
        System.out.println(setOps);

        return exp;
    }
}
like image 652
user3287300 Avatar asked May 20 '26 04:05

user3287300


1 Answers

An example similar to yours:

public class DemoSplit  {   
    public static void main(String[] args) {
        String s = ",1,2,";
        String su[] = s.split(",");
        for (String st: su) System.out.println("'"+st+"'");
    }
}

Will print:

''
'1'
'2'

The first char is a delimiter, so split there and the element before it is the first element of th esplitted array.

In your case you spliut on numbers:

9+3*2/1

before 9, empty element, after '+' ...

If you feel like looking at the code, String.split calls java.util.regex.Pattern.split

In the split method, you will see that adds to an ArrayList the subStrings between index and the match, since index is zero for the first iteration and the first match in the example is at zero, the first element is an empty string. From the source code of the split method:

    ArrayList<String> matchList = new ArrayList<String>();
    Matcher m = matcher(input);

    // Add segments before each match found
    while(m.find()) {
        if (!matchLimited || matchList.size() < limit - 1) {
            String match = input.subSequence(index, m.start()).toString();
            matchList.add(match);
            index = m.end();
        } else if (matchList.size() == limit - 1) { // last one
            String match = input.subSequence(index,
                                             input.length()).toString();
            matchList.add(match);
            index = m.end();
        }
    }
like image 81
Raul Guiu Avatar answered May 21 '26 18:05

Raul Guiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!