import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* 给定一些分割符,给定一个待分割的字符串,打印出分割之后最长的字符串(多个则换行输出)
*/
public class TokenLongest {
public static void main(String[] args) {
String delimiters = ",. \"";
String str = "The string tokenizer class allows an application to break a string into tokens.";
printTokenLongest(str, delimiters);
}
private static void printTokenLongest(String str, String delim) {
StringTokenizer stringTokenizer = new StringTokenizer(str, delim);
List<String> list = new ArrayList<>();
String temp;
int length = 0, maxlength = 0;
while (stringTokenizer.hasMoreTokens()) {
temp = stringTokenizer.nextToken();
if (!list.isEmpty() && (length = temp.length()) < (maxlength = list.get(0).length())) {
continue;
} else if (length > maxlength) {
list.clear();
}
list.add(temp);
}
list.forEach(System.out::println);
}
}
/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */