📜  Java中的 StringTokenizer 类

📅  最后修改于: 2022-05-13 01:54:31.726000             🧑  作者: Mango

Java中的 StringTokenizer 类

Java中的 StringTokenizer 类用于将字符串分解为标记。 StringTokenizer 对象在内部维护要标记化的字符串中的当前位置。一些操作将当前位置推进到处理的字符之后。通过获取用于创建 StringTokenizer 对象的字符串的子字符串来返回令牌。

插图:

字符串分词器

StringToken 的构造函数:让我们认为 'str' 是要标记的字符串

  1. StringTokenizer(String str):默认分隔符,如换行符、空格、制表符、回车符和换页符。
  2. StringTokenizer(String str, String delim): delim 是一组用于标记给定字符串的分隔符。
  3. StringTokenizer(String str, String delim, boolean flag):前两个参数含义相同,其中flag
    服务于以下目的。

3.1:如果标志为假,分隔字符用于分隔标记

例子:

Input : if string --> "hello geeks" and Delimiter is " ", then 
Output:  tokens are "hello" and "geeks".

3.2:如果标志为真,分隔字符被认为是记号。

例子:

Input : String --> is "hello geeks"and Delimiter is " ", then 
Output: Tokens --> "hello", " " and "geeks".

StringTokenizer 类的方法

MethodAction Performed
countTokens()Returns the total number of tokens present
hasMoreToken()Tests if tokens are present for the StringTokenizer’s string
nextElement()Returns an Object rather than String
hasMoreElements()Returns the same value as hasMoreToken
nextToken()Returns the next token from the given StringTokenizer. 

执行:

Java
// Java Program to Illustrate StringTokenizer Class
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Constructor 1
        System.out.println("Using Constructor 1 - ");
 
        // Creating object of class inside main() method
        StringTokenizer st1 = new StringTokenizer(
            "Hello Geeks How are you", " ");
 
        // Condition holds true till there is single token
        // remaining using hasMoreTokens() method
        while (st1.hasMoreTokens())
 
            // Getting next tokens
            System.out.println(st1.nextToken());
 
        // Constructor 2
        System.out.println("Using Constructor 2 - ");
 
        // Again creating object of class inside main()
        // method
        StringTokenizer st2 = new StringTokenizer(
            "JAVA : Code : String", " :");
 
        // If tokens are present
        while (st2.hasMoreTokens())
 
            // Print all tokens
            System.out.println(st2.nextToken());
 
        // Constructor 3
        System.out.println("Using Constructor 3 - ");
 
        // Again creating object of class inside main()
        // method
        StringTokenizer st3 = new StringTokenizer(
            "JAVA : Code : String", " :", true);
 
        while (st3.hasMoreTokens())
            System.out.println(st3.nextToken());
    }
}


输出
Using Constructor 1 - 
Hello
Geeks
How
are
you
Using Constructor 2 - 
JAVA
Code
String
Using Constructor 3 - 
JAVA
 
:
 
Code
 
:
 
String