CherryBomb95
CherryBomb95

Reputation: 163

getting a number out of any string

Okay, so lets say I have the string 7 + 8 = 15 and I wanted to be able to get the second number, in this case 8, out of string to use. I also want to be able to do this over any string, like 64 - 29 = 35 or 12 * 12 = 144.

However there are some constraints. I can't use arrays, try/catch, SystemTokenizer, or regex.

I've tried using .substring but this seems like it can only have one set location, so I am at a loss.

String str = "7 + 8 = 15";

    int whiteSpace1 = str.indexOf(" ");
    int first = Integer.parseInt(str.substring(0, whiteSpace1));

I know that this will give me the first number, 7. However, I do not know how to get the second number in order to compute them so that I may check the math against the answer after the =

And no, the spaces between the numbers will not always be present.

(I know this is very odd, but for some reason my Intro to CS teacher seems to think this is a wonderful assignment)

Upvotes: 1

Views: 112

Answers (3)

RandomQuestion
RandomQuestion

Reputation: 6988

if there is space on each side of operator and equal sign then you can do something like

String s = "7 + 5 = 12";
s = s.substring(0, s.indexOf("=")).trim();
int number = Integer.parseInt(s.substring(s.lastIndexOf(" ") + 1))

Above should work irrespective of operator.

If there are no spaces, then you would have to loop through each character to find first non-integer character and start building number. OR you can write separate code for each operator to avoid looping.

Upvotes: 1

Adarsh
Adarsh

Reputation: 3641

You can use regex for this operation.

s.split("[-+=*]")[1]

The split function uses the regex to identify all matches and splits it accordingly using each of the regex characters as a delimiter. It returns a String array of all the delimited values. You need the second value in the array.

Just keep adding the operands you might encounter between the first and the second number in your string within [].

Upvotes: 0

Trying
Trying

Reputation: 14278

if the string is:

String str1 = "64-29=35"; //no space before = and after -

System.out.println(str1.substring(str1.indexOf("-")+1, str1.indexOf("=")));

output:

29

if the string is :

String str1 = "64 - 29 = 35";//with spaces

Than

System.out.println(str1.substring(str1.indexOf("-")+2, str1.indexOf("=")-1));

Upvotes: 1

Related Questions