E
E
Evgeny Velichko2020-03-05 20:14:47
Java
Evgeny Velichko, 2020-03-05 20:14:47

How to extract the "+" operator from a string?

String a = "5+3";

I am writing a calculator. How to convert a string to a mathematical expression?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Cheremisin, 2020-03-05
@leahch

If it's simple - break the line through regexp.

String text = "5+(2-3*8/10)/123=ERR";
    Pattern pattern = Pattern.compile("[+|\\-|\\*|/|=|\\(|\\)]");
    Matcher matcher = pattern.matcher(text);
    
    int prev = 0;
    while(matcher.find()) {
      String operator = text.substring(matcher.start(), matcher.end());
      String operand = text.substring(prev, matcher.start());
      System.out.printf("Operand: '%s', operator: '%s'\n", operand, operator);
      prev = matcher.end();
    }
    if(prev > 0 && prev < text.length()) {
      String last = text.substring(prev, text.length());
      System.out.printf("Last: %s\n", last);
    }

Operand: '5', operator: '+'
Operand: '', operator: '('
Operand: '2', operator: '-'
Operand: '3', operator: '*'
Operand: '8', operator: '/'
Operand: '10', operator: ')'
Operand: '', operator: '/'
Operand: '123', operator: '='
Last: ERR

Well, if for an adult - then you are in antlr - https://www.antlr.org/ or javaCC - https://javacc.github.io/javacc/
Shl. for antlr there is a grammar file for the calculator - https://github.com/antlr/grammars-v4/tree/master/c...
And to read - https://www.baeldung.com/java-antlr

S
Stavr Strelov, 2020-03-05
@IAmNoob

If you mean to split a string into characters by sign, then you need the split(String regex) method:
String a "5+3";
String[] a1 = a.split("");
System.out.println(a1[0]);
System.out.println(a1[1]);
System.out.println(a1[2]);
Output:
5
+
3
To clarify: the split(String regex) method splits the string by the character(s) you supply as an argument. This method returns an array of the received strings. If you insert an empty string as an argument, it will return an array of characters from the string "5+3": {"5", "+", "3"} ! And then you can do with them what you want)

C
Cheypnow, 2020-03-05
@Cheypnow

If you need parsing along with brackets and characters with different precedence, look better towards reverse Polish notation .
One of the implementation examples in java

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question