Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Selecting characters from a string

Doug Wolfinger
Greenhorn
Posts: 18
Hello,
I've copied this from the Beginners forum, as I malignantly posted it there originally.
I am trying to pass a string that represents a postfix expression. The method that accepts it should take each number and place it on the stack. When it encounters an operator, it should pop the top two numbers and evaluate them with the operator.
This is the expression. "abc+-"
a=7, b=3, c=12 So it applies "+" to c and b, then it subtracts (c + b) from a. I have made the string into a string array in my program, but I think the idea is to pass the expression as a regular string as I have it above. I would use substring(), but that doesn't work with a number larger than 2 digits. Thanks!

Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
If you pass in a String vs. a String array the you have to delimit the numbers somehow. Because otherwise you wouldn't know what numbers are supposed to be together. For example:
a=7, b=3, c=12
7312+-
I could interpret that as:
a=7,b=31,c=2 or a=73,b=1,c=2
But if the numbers are delimited the theres no questions, lets say they are delimited by commas then your argument will be
7,3,12+-, so you know for sure that a=7, b=3, and c=12.
Do you have a choice on how you are getting(generating?) this String input?
If you know for sure that you will be given a String input that will contain numbers that only contain one digit per integer then you can use your current code and just create a String [] from the String.

Ilja Preuss
author
Sheriff
Posts: 14112
If you can use the same delimiter for operators and operands (spaces, for example: "12 3 4 + -"), you can use a StringTokenizer to decompose the String.