Ignore parentheses with string tokenizer?

孤街醉人 提交于 2019-12-24 15:52:06

问题


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


回答1:


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:

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());
    }
}

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)




回答2:


How about

 for(String number: transitionInput
       .replace('(', ' ').replace(')', ' ').split("\\s+")){
    transition.add(number);
 }



回答3:


Another variant

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;


public class simple {


 public static void main(String[] args)
 {

  List transition = new ArrayList();
     String transitionInput="(0 0 0)";
     transition = Arrays.asList((transitionInput.substring(1,transitionInput.length()-1)).split("\\s+"));
     System.out.println(transition);
 }
}

Output : [0, 0, 0]




回答4:


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;


public class simple {


 public static void main(String[] args)
 {

  List transition = new ArrayList();
     String transitionInput="(0 0 0)";
     transition = Arrays.asList((transitionInput.substring(1,transitionInput.length()-1)).split("\\s+"));
     System.out.println(transition);
 }
}


来源:https://stackoverflow.com/questions/4003159/ignore-parentheses-with-string-tokenizer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!