在地图中构建堆栈
我有一个看起来像这样的字符串:
"7-6-4-1"
or
"7"
or
""
即一组用 - 分隔的数字。可能有零个或多个数字。
我想返回一个堆栈,其中的数字按该顺序推送(即,第一个示例中,先推送 7,然后推送 1 ast)
如果我只想返回一个列表,我可以直接 str.split("-" ).map{_.toInt}
(尽管这对空字符串不起作用)/
但是没有 toStack 可以转换为 Stack。所以目前,我有
{
val s = new Stack[Int];
if (x.nonEmpty)
x.split('-').foreach {
y => s.push(y.toInt)
}
s
}
Which 有效,但相当丑陋。我缺少什么?
编辑:感谢所有回复者,我从这次讨论中学到了很多东西
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要忘记方便的
breakOut
,它提供比col: _*
稍好的性能(请参阅 Daniel 的出色解释)此处与 Rex Kerr 的
.filterNot(_.isEmpty)
解决方案一起使用:将输出:
Dont forget the ever handy
breakOut
which affords slightly better performance thancol: _*
(see Daniel's excellent explanation)Used here with Rex Kerr's
.filterNot(_.isEmpty)
solution:Will output:
这里的技巧是将 split 获得的数组传递到 Stack 伴随对象构建器中。默认情况下,项目的放入顺序与数组相同,因此您必须首先反转数组。
请注意“将其视为一个列表,而不是单个项目”注释
: _*
。编辑:如果您不想单独捕获空字符串情况,如下所示(使用底部的可变堆栈,顶部的不可变堆栈):
那么您可以过滤掉空字符串:
这也将“有助于”处理类似的事情
7-9----2-2-4
为您提供(它将给出Stack(4,2,2,9,7)
)。如果您想处理更卑鄙的格式错误,您可以
仅返回那些实际上可以解析的项目。
The trick here is to pass the array you get from split into the
Stack
companion 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-4
for 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.