hello world
hello world

Reputation: 316

How to split numbers from a string in Java?

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.

Upvotes: 5

Views: 14552

Answers (6)

xadun
xadun

Reputation: 146

I'm creating a Calculator too and I'm using Stacks to split the equation into Numbers and Operators, just like @Gaurav said. Here's the code that I'm using:

for (int i=0; i<equation.length(); i++) {

            equationChar = String.valueOf(equation.charAt(i));

            if (numbers.contains(equationChar)) {

                equationHold += equationChar;

                if (i==(equation.length()-1)) {

                    stackNumbers.push(equationHold);    
                }

            } else {

                stackNumbers.push(equationHold);
                stackOperators.push(equationChar);
                equationHold = "";

            }

        }

I found it much easer than dealing with the String Split expressions. I'm not dealing with the brackets and stuff yet, so the code may change..

Upvotes: 0

shounak
shounak

Reputation: 51

Pattern pp = Pattern.compile("\\d+");
Matcher m = pp.matcher("sdfsdf123sdfs3464ew111");
While(m.find())
{
    System.out.println(m.group());
}

output will be:

123
3464
111

check out !

Upvotes: -1

Giorgio
Giorgio

Reputation: 5173

You can use regular expressions. Here is a (very rough) sketch:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String findIntegerOccurrence(String inputString)
{
    // Define pattern to match your numbers here.
    Pattern pattern = Pattern.compile("... reg expr here...");
    Matcher matcher = pattern.matcher(inputString);

    if (matcher.find()) // Checks if the regular expression matches.
    {
        // Extract the substring of inputString that has matched
        return matcher.group();
    }
    else
    {
        return null;
    }
}

You basically need to define an appropriate regular expression for your numbers and then use it to find all occurrences inside the input string. The above example is only a sketch to see how you define a regular expression and match it. Since you want to match all occurrences of numbers and separate them from the rest of the input, you will need a more elaborate solution (the above example only shows which classes you need and some useful methods).

You can find all the details on regular expressions in Java in the Java documentation

EDIT

Removed edit: I had added a description of the needed regular expression but the same regular expression has been added as a comment to another answer a few minutes before I could complete my changes. Please refer to the other answer.

Upvotes: 1

Arne Deutsch
Arne Deutsch

Reputation: 14769

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());
  }
}

Upvotes: 3

Ewald
Ewald

Reputation: 5751

If you do not need the non-numeric characters, do the following:

Parse the string once, replacing all non-numeric characters with a space. The, parse the resulting string, removing double spaces as you go along. the input string gi356f would first become _356, with _ being spaces. If you then remove the double spaces, you'd have what you were looking for.

Another example d45*9j becomes _45_9_ and then, when you split it into substrings, you will have 45 and 9 and seperate numbers.

There are many ways to do this, the best way is to try different approaches until you find something that works for you.

Upvotes: 0

Gaurav
Gaurav

Reputation: 1567

A stack data structure may help here. So here is what you can do:

  1. Scan every character.
  2. Check if the char is number. If yes, put in stack.
  3. Continue adding the char to stack until you get any non-numeric character.
  4. Once you get non-numeric character, take out all numeric chars from stack and convert to number.
  5. Continue till the char is not finished.

Upvotes: 2

Related Questions