提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过StringTokenizer将给定字符串标记化为字符串数组。
//package com.nowjava; import java.util.ArrayList; import java.util.Collection; /*来自 nowjava.com - 时代Java*/ import java.util.List; import java.util.StringTokenizer; public class Main { public static void main(String[] argv) { String str = "nowjava.com"; String delimiters = "."; System.out.println(java.util.Arrays.toString(tokenizeToStringArray( str, delimiters))); } public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { /* N o w J a v a . c o m 提供 */ if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList<String>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return toStringArray(tokens); }