I'm having problems thinking of a way to split numbers of string. What I have done already is split the string into multiple characters.
so if the expression was gi356f
it would give:
g
i
3
5
6
f
But I want the 356 to be considered as a number in it's own respect. and the problem I'm dealing with consists of strings that look like (345+3)*/3
I tried looking at the current character in the string and the next, and tried checking whether it's a digit and if so, attached them but this led to many errors. for instance it would only handle two digit long numbers and also not so well, if the string was 43, it would use the 3 twice. (e.g once for 43 and again for 3 on it's on). Also if the expression at the end ended with a number of a given string if would be handled twice also.
I'm not sure how to address this problem. I think maybe use regex or scanner but not sure how to go about it, even after looking at some code online of smaller examples.
You may use regular expressions for this. Here is the solution for the simple case (just integers). The \\d
is an decimal and the plus +
says once or more. For more information look at http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html .
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("(345+3)*/3");
while(m.find())
System.out.println(m.group());
}
}
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