简体   繁体   English

StringTokenizer问题

[英]StringTokenizer questions

I am facing some problems in String tokenizer like if I code is following then there are some questions which I want to know. 我在String标记生成器中遇到一些问题,例如如果我遵循以下代码,那么我想知道一些问题。

Code : 代码

public class Str_Tokenizer {
    public static void main(String args[]){
        StringTokenizer st=new StringTokenizer("this is him");
        while(st.hasMoreTokens()) {
            System.out.println(st.nextToken());
        }
    }
}

Questions: 问题:

  1. If I don't use the while(st.hasMoreTokens()) then how I can use StringTokenizer ? 如果我不使用while(st.hasMoreTokens())那么如何使用StringTokenizer
  2. If I don't use st.nextToken , what I should use? 如果我不使用st.nextToken ,我应该使用什么?

StringTokenizer is a legacy class that is retained for compatibility reasons StringTokenizer是一个遗留类,出于兼容性原因而保留

First you cannot use that class without those hasMoreTokens() and next() method. 首先,如果没有那些hasMoreTokens()next()方法,则无法使用该类。

You cannot loop on it as a alternative because hasMoreElements() Returns the same value as the hasMoreTokens method. 您不能对其进行循环,因为hasMoreElements()返回与hasMoreTokens方法相同的值。 nextElement() Returns the same value as the nextToken method and you don't want to use them. nextElement()返回与nextToken方法相同的值,并且您不想使用它们。

other wise hasMoreElements and nextElement are alternatives. 其他明智的hasMoreElementsnextElement是替代方案。

Although its use is discouraged in new code. 尽管在新代码中不鼓励使用它。 It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. 建议任何寻求此功能的人改用String的split方法或java.util.regex包。

Even docs of StringTokenizer given example how you can avoid to use it 甚至StringTokenizer的文档都给出了如何避免使用它的示例

The following example illustrates how the String.split method can be used to break up a string into its basic tokens: 下面的示例说明如何使用String.split方法将字符串分解成其基本标记:

 String[] result = "this is a test".split("\\s");
 for (int x=0; x<result.length; x++)
     System.out.println(result[x]);

If you don't want to use while and nextToken , go for String split. 如果您不想使用whilenextToken ,请进行字符串拆分。 this way: 这条路:

String s ="this is him";
        String[] s2 = s.split(" ");
        for (String str : s2) {
            System.out.println(str);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM