I need to find all numbers in string and do simple arithmetic with them. If count of the symbols between two numbers are even, then operator is '+', if count is odd, then operator is '-'.
Input: 10plus5 - Output: 15; (10 + 5);
Input: 10i5can3do2it6 - Output: 10; (10 - 5 - 3 + 2 + 6);
Input: 10i5can3do2it - Output: 4; (10 - 5 - 3 + 2);
I can find solution only for the first example:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int result = 0;
int count = 0;
Pattern pat = Pattern.compile("([\\d]+)([\\D]+)([0-9]+)");
Matcher match = pat.matcher(input);
while(match.find()){
char[] array = match.group(2).toCharArray();
for (int i = 0; i < array.length; i++) {
int firstNumber = Integer.parseInt(match.group(1));
int secondNumber = Integer.parseInt(match.group(3));
count++;
if(count % 2 == 0){
result = firstNumber + secondNumber ;
}else{
result = firstNumber - secondNumber;
}
}
}
System.out.println(result);
}