Answer the question
In order to leave comments, you need to log in
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
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
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question