5

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.

3
  • 1
    If you show what you've already tried someone might help you. Commented Jan 3, 2012 at 12:31
  • Do you just want to extract the numbers, or do you want to analyze the string? Commented Jan 3, 2012 at 12:37
  • i want to just extract the numbers, i just considered another thing i need handle negatives and decimals. so if the expression was (-1.53 +3) i want to be able to extract -1.53 3 not entirely sure on how to check whether if the number in my character parser has finished. Commented Jan 3, 2012 at 12:38

6 Answers 6

3

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());
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i understand this, but with this, not sure on handling numbers which have combination of - and decimals. e.g dealing with numbers such as -3.45. have i missed something?
The only thing you have to do is to extend the regular expression. Should be simple. Without testing something like [+-]?\\d+(\\.\\d+)?. Just read the documentation about regular expressions. They are designed exactly for this type of problems.
2

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.

4 Comments

i was trying to implement like how you've described, im struggling to think test condition on checking whether i mean a negative number or the operator minus. since, im trying to store the operators in another stack and numbers in another. but i want to treat -1.54 as a number and store it in a stack
@hello world : Can you throw more light on exact problem domain. There must some restriction on the incoming string . Is it a mathematical expression or just a stream of characters.
it's a mathematical expression calculator, e.g it can be (-1.54+3*4/2)
In that case one should follow some rules of defining mathematical expression. For example: It's never written as 5--7. It's 5-(-7).
1

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.

Comments

0

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.

Comments

0

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..

Comments

-1
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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.