I have a string that looks like this:
"7-6-4-1"
or
"7"
or
""
That is, a set of numbers separated by -. There may be zero or more numbers.
I want to return a stack with the numbers pushed on in that order (i.e. push 7 first and 1 ast, for the first example)
If I just wanted to return a list I could just go str.split("-").map{_.toInt} (although this doesn’t work on the empty string)/
There’s no toStack to convert to a Stack though. So currently, I have
{
val s = new Stack[Int];
if (x.nonEmpty)
x.split('-').foreach {
y => s.push(y.toInt)
}
s
}
Which works, but is pretty ugly. What am I missing?
EDIT: Thanks to all the responders, I learnt quite a bit from this discussion
The trick here is to pass the array you get from split into the
Stackcompanion object builder. By default the items go in in the same order as the array, so you have to reverse the array first.Note the “treat this is a list, not as a single item” annotation,
: _*.Edit: if you don’t want to catch the empty string case separately, like so (use the bottom one for mutable stacks, the top for immutable):
then you can filter out empty strings:
which will also “helpfully” handle things like
7-9----2-2-4for you (it will giveStack(4,2,2,9,7)).If you want to handle even more dastardly formatting errors, you can
to return only those items that actually can be parsed.