StringTokenizer類詳解

StringTokenizer類是一個用來對String進行分詞編輯的應用類,類似於Java String 類中的split函數.

構造函數

StringTokenizer提供了三個構造參數

public StringTokenizer(String str)
public StringTokenizer(String str, String delim)
public StringTokenizer(String str, String delim, boolean returnDelims)

其中,前兩個構造函數直接調用第三個構造函數創建一個StringTokenizer實例.參數str代表要分割的字符串,delim爲一個分割標識符集合,returnDelims表示是否返回分割標識符.在沒有指定分割標識符的情況下,默認是"\t\n\r\f".

常用方法

首先,先理解本類中Token的概念.StringTokenizer類的作用就是對給定的字符串進行分割,而分割後的元素就是Token.比如"This is a java programmer!“這個字符串按照空格來分割,那個分割後就是"This”,“is”,“a”,“java”,"programmer!"五個字符串,也就是5個Token.

現在來看一下常用的方法

public boolean hasMoreTokens()//是否還有Token
public String nextToken()//下一個Token
public String nextToken(String delim)//根據分隔符獲取下一個Token
public int countTokens()//Token的總個數

代碼示例

demo1

本例演示了使用默認分隔符對字符串進行分割以及分割後的處理

String content = "Both sides reached consensus on market access and the text of free trade agreement, " +
                "making a substantive progress and a basic completion of the FTA negotiation.";
StringTokenizer st = new StringTokenizer(content);
System.out.println("分割後Token的個數-->"+st.countTokens());
int i=1;
while(st.hasMoreElements()){
    String token = st.nextToken();
    System.out.print(i+"."+token+" ");
    i++;
}

輸出內容如下:

分割後Token的個數-->26
1.Both 2.sides 3.reached 4.consensus 5.on 6.market 7.access 8.and 9.the 10.text 11.of 12.free 13.trade 14.agreement, 15.making 16.a 17.substantive 18.progress 19.and 20.a 21.basic 22.completion 23.of 24.the 25.FTA 26.negotiation. 

demo2

使用指定的分隔符分割字符串

String content = "https://blog.jetbrains.com/idea/2009/04/global-unused-declaration-inspection/";
	StringTokenizer st = new StringTokenizer(content,"/");
	System.out.println("分割後Token的個數-->" + st.countTokens());
	int i = 1;
	while (st.hasMoreElements()) {
		String token = st.nextToken();
		System.out.print(i + "." + token + " ");
		i++;
	}
}

輸出內容如下:

分割後Token的個數-->6
1.https: 2.blog.jetbrains.com 3.idea 4.2009 5.04 6.global-unused-declaration-inspection 

demo3

String content = "https://blog.jetbrains.com/idea/2009/04/global-unused-declaration-inspection/";
StringTokenizer st = new StringTokenizer(content,"/",true);
System.out.println("分割後Token的個數-->" + st.countTokens());
int i = 1;
while (st.hasMoreElements()) {
    String token = st.nextToken();
    System.out.print(i + "." + token + " ");
    i++;
}

輸出內容:

分割後Token的個數-->13
1.https: 2./ 3./ 4.blog.jetbrains.com 5./ 6.idea 7./ 8.2009 9./ 10.04 11./ 12.global-unused-declaration-inspection 13./ 

參考文章:http://blog.csdn.net/riyunzhu/article/details/7989145

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章