I am making a calculator sort of app for android and got stuck for evaluating expression which comes by entering numbers and different signs.I have string as "10+5-35*2+80/4" and want to separate all numbers and signs so that I can solve the expression.
more specific.... number can be any number between [0-9] of any digit and any operator can be there.
You can iterate over the string and use the following:
for(Character ch : inputString.toCharArray())
if (Character.isDigit(ch))
// ...
List<String> numbers = new ArrayList<>();
List<String> operators = new ArrayList<>();
String str = "1+2/300%4";
char[] strCharArray = str.toCharArray();
StringBuilder numbersSb = new StringBuilder();
for (int i = 0; i < strCharArray.length; i++) {
if (Character.isDigit(strCharArray[i])) {
numbersSb.append(strCharArray[i]);
} else {
operators.add(String.valueOf(strCharArray[i]));
numbers.add(numbersSb.toString());
numbersSb = new StringBuilder();
}
if (i == strCharArray.length - 1 && !numbersSb.toString().isEmpty()) {
numbers.add(numbersSb.toString());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.