Playdowin
Playdowin

Reputation: 94

Java: Find Integers in a String (Calculator)

If I have a String that looks like this: String calc = "5+3". Can I substring the integers 5 and 3?

In this case, you do know how the String looks, but it could look like this: String calc = "55-23" Therefore, I want to know if there is a way to identify integers in a String.

Upvotes: 1

Views: 616

Answers (3)

Farnad Tohidkhah
Farnad Tohidkhah

Reputation: 1269

You can read each character and find it's Ascii code. Evaluate its code if it is between 48 and 57, it is a number and if it is not, it is a symbol. if you find another character that is a number also you must add to previous number until you reach a symbol.

    String calc="55-23";
    String intString="";
    char tempChar;
    for (int i=0;i<calc.length();i++){
        tempChar=calc.charAt(i);
        int ascii=(int) tempChar;
        if (ascii>47 && ascii <58){
            intString=intString+tempChar;
        }
        else {
            System.out.println(intString);
            intString="";
            }
    }

Upvotes: 1

Tim
Tim

Reputation: 5681

You could use a regex like ([\d]+)([+-])([\d]+) to obtain the full binary expression.

Pattern pattern = Pattern.compile("([\\d]+)([+-])([\\d]+)");

String calc = "5+3";

Matcher matcher = pattern.matcher(calc);

if (matcher.matches()) {

    int lhs = Integer.parseInt(matcher.group(1));
    int rhs = Integer.parseInt(matcher.group(3));

    char operator = matcher.group(2).charAt(0);

    System.out.print(lhs + " " + operator + " " + rhs + " = ");

    switch (operator) {

        case '+': {
            System.out.println(lhs + rhs);
        }

        case '-': {
            System.out.println(lhs - rhs);
        } 
    }
}

Output:

5 + 3 = 8

Upvotes: 1

Andreas
Andreas

Reputation: 159096

For something like that, regular expression is your friend:

String text = "String calc = 55-23";
Matcher m = Pattern.compile("\\d+").matcher(text);
while (m.find())
    System.out.println(m.group());

Output

55
23

Now, you might need to expand it to support decimals:

String text = "String calc = 1.1 + 22 * 333 / (4444 - 55555)";
Matcher m = Pattern.compile("\\d+(?:.\\d+)?").matcher(text);
while (m.find())
    System.out.println(m.group());

Output

1.1
22
333
4444
55555

Upvotes: 2

Related Questions