How to split a string?
I've got a String:
String s = "1+2*3(30+4/2-(10+2))*2+1";
Got method which get digit values from String:
private static DigitStack getNumber(String convert) {
String[] arr = convert.split("");
digitStack = new DigitStack();
try {
for (int i = 0; i < arr.length ; i++) {
while (arr[i].matches("\\d+")) {
digitStack.push(Double.valueOf(arr[i]));
i++;
}
}
}catch (Exception e){
e.printStackTrace();
}
return digitStack;
}
method return values:
1.0; 2.0; 3.0; [3.0 0.0]; 4.0; 2.0; [1.0 0.0]; 2.0; 2.0; 1.0;
expected output:
1.0; 2.0; 3.0; 30.0; 4.0; 2.0; 10.0; 2.0; 2.0; 1.0;
Problem is method count every symbol like separate, and number 30 and 10. It convert in two numbers [3.0 and 0.0] [1.0 and 0.0]
How to fix it?
Simplest way would be to split your string on non-digits i.e.
String s = "1+2*3(30+4/2-(10+2))*2+1";
String[] arr = s.split("\\D+");
This will return an array
[1, 2, 3, 30, 4, 2, 10, 2, 2, 1]
which you can then iterate through and convert to double.
As Rohit pointed out this approach will not work if you have numbers with decimal points or if you want to consider also negative numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With