使用字符串标记器忽略括号? [英] Ignore parentheses with string tokenizer?

查看:26
本文介绍了使用字符串标记器忽略括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入看起来像:(0 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(","));
    }

然而,输出看起来像这样 [(0 0 0)]
我想忽略括号

However, the output looks like this [(0 0 0)]
I would like to ignore the parentheses

推荐答案

您首先使用 () 作为分隔符,然后切换到 ,,但您在切换之前提取第一个标记(括号之间的文本).

You are first using () as delimiters, then switching to ,, but you are switching before extracting the first token (the text between parentheses).

您可能打算这样做:

transitionInput = data.nextLine();
st = new StringTokenizer(transitionInput,"()", false);
if (st.hasMoreTokens())
{
    String chunk = st.nextToken();
    st = new StringTokenizer(chunk, ",");
    while (st.hasMoreTokens())
    {
        transition.add(st.nextToken());
    }
}

此代码假定表达式始终以括号开头和结尾.如果是这种情况,您也可以使用 String.substring() 手动删除它们.此外,您可能需要考虑使用 String.split() 进行实际拆分:

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 using String.split() to do the actual splitting:

String transitionInput = data.nextLine();
transitionInput = transitionInput.substring(1, transitionInput.length() - 1);
for (String s : transitionInput.split(","))
    transition.add(s);

请注意,这两个示例都假定逗号用作分隔符,如您的示例代码(尽管您的问题文本另有说明)

Note that both examples assume that commas are used as separators, as in your sample code (although the text of your question says otherwise)

这篇关于使用字符串标记器忽略括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆