I’m trying to write a method that does addition, and subtraction
using indexOf() , lastIndexOf()
for example string s = “3 + 3”
I want to break this string into two substrings then do certain operation.
// for addition
String s = "3 + 3";
int indexOfPlus = s.indexOf('+');
String beforePlus = s.substring(0,indexOfPlus);
String afterPlus= s.substring(indexOfPlus+1);
.....
.....
// for subtraction
String s = "3 - 3";
int indexOfMinus = s.indexOf('-');
String beforeMinus = s.substring(0,indexOfMinus);
String afterMinus = s.substring(indexOfMinus+1);
....
....
My QUESTION IS:
However, I’m not sure how should I break the string such as “3+ -1” or “3- +1” into
substrings.
first of all I would advise to use separate fields for each operand and operation, that way you won’t have to split anything and just parse the numbers.
there is something called regex, although it’s a little advanced it will enable you to do these operations much easier using the method String.split() , this method takes a regex as a parameter and returns the splitted strings as array, for instance (“5+5”).split(“[-+]”) will return 5 and 5 each as a String.