Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split numbers from a string in Java?

Tags:

java

string

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.

like image 496
hello world Avatar asked Jan 03 '12 12:01

hello world


1 Answers

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());
  }
}
like image 138
Arne Deutsch Avatar answered Oct 11 '22 16:10

Arne Deutsch