Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a infix String to an array of String in java

I am working on a mini scientific calculator which works on infix to postfix algorithm. My input is an infix string .. and my infix to postfix conversion logic requires an array of string. So how can i split an infix string like this:

 100+(0.03*55)/45-(25+55)

To an array of String in which each operand and operator is an array element. like this

 "100" , "+" , "(" , "0.03" , "*" , "55" , ")" , "/" , "45" , "-"

and so on...

Note that there is no space in the string so it can't be split on the basis of regex " ".

like image 409
Afzal Ashraf Avatar asked Mar 19 '26 01:03

Afzal Ashraf


2 Answers

Apparently each character is an apart token, except for consecutive digits with possibly a dot. So a simple solution would be iterating over the string, and then when you see a digit that is preceded by another digit (or the decimal separator, a dot), you add the character to the previous token, otherwise add it to a new token.

Here the code:

public static List<String> getTokens(String inputString) {
    List<String> tokens = new ArrayList<String>();
    // Add the first character to a new token. We make the assumption
    // that the string is not empty.
    tokens.add(Character.toString(inputString.charAt(0)));

    // Now iterate over the rest of the characters from the input string.
    for (int i = 1; i < inputString.length(); i++) {
        char ch = inputString.charAt(i); // Store the current character.
        char lch = inputString.charAt(i - 1); // Store the last character.

        // We're checking if the last character is either a digit or the
        // dot, AND if the current character is either a digit or a dot.
        if ((Character.isDigit(ch) || ch == '.') && (Character.isDigit(lch) || lch == '.')) {
            // If so, add the current character to the last token.
            int lastIndex = (tokens.size() - 1);
            tokens.set(lastIndex, tokens.get(lastIndex) + ch);
        }
        else {
            // Otherwise, add the current character to a new token.
            tokens.add(Character.toString(ch));
        }
    }
    return tokens;
}

Note that this method is faster than most regular expression methods.

like image 181
MC Emperor Avatar answered Mar 20 '26 14:03

MC Emperor


You can use regex for parsing a mathamatical expression stored in a string.

expString.split("(?<=[-+*/\\(\\)])|(?=[-+*/\\(\\)])");

will do the trick for you.

Say,

String str = "100+(0.03*55)/45-(25+55)";
String[] outs = str.split("(?<=[-+*/\\(\\)])|(?=[-+*/\\(\\)])");
for (String element : outs)
{
    System.out.println(element);
}

Will give you an output of,

100
+
(
0.03
*
55
)
/
45
-
(
25
+
55
)

Please check my experiment @ http://rextester.com/QEMOYL38160

like image 24
Let'sRefactor Avatar answered Mar 20 '26 13:03

Let'sRefactor