使用字符串标记器忽略括号?
我的输入如下所示:(0 0 0)
我想忽略括号,只将数字(在本例中为 0)添加到数组列表中。
我正在使用扫描仪从文件中读取数据,这就是我到目前为止所拥有的
transitionInput = data.nextLine();
st = new StringTokenizer(transitionInput,"()", true);
while (st.hasMoreTokens())
{
transition.add(st.nextToken(","));
}
但是,输出看起来像这样 [(0 0 0)]
我想忽略括号
I have an input that looks like: (0 0 0)
I would like to ignore the parenthesis and only add the numbers, in this case 0, to an arraylist.
I am using scanner to read from a file and this is what I have so far
transitionInput = data.nextLine();
st = new StringTokenizer(transitionInput,"()", true);
while (st.hasMoreTokens())
{
transition.add(st.nextToken(","));
}
However, the output looks like this [(0 0 0)]
I would like to ignore the parentheses
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样
How about
您首先使用
()
作为分隔符,然后切换到,
,但您是在提取第一个标记(括号之间的文本)之前切换的。您可能想要做的是:
此代码假定表达式始终以括号开头和结尾。如果是这种情况,您也可以使用 String.substring() 手动删除它们。另外,您可能需要考虑使用
String.split()
进行实际的拆分:请注意,这两个示例都假设使用逗号作为分隔符,如示例代码中所示(尽管您的文本问题另有说明)
You are first using
()
as delimiters, then switching to,
, but you are switching before extracting the first token (the text between parentheses).What you probably intended to do is this:
This code assumes that the expression always starts and ends with parentheses. If this is the case, you may as well remove them manually using
String.substring()
. Also, you may want to consider usingString.split()
to do the actual splitting:Note that both examples assume that commas are used as separators, as in your sample code (although the text of your question says otherwise)
另一种变体
输出:[0, 0, 0]
Another variant
Output : [0, 0, 0]