简体   繁体   中英

Java StringTokenizer with 2 params?

I know using StringTokenizer is not a great idea, but I need to use it. Is it possible to "destroy" all the ' ' and '\\t' characters and split the string? For example:

"Hello \\t \\t this\\tis great"

Should be:

"Hello"
"this"
"is"
"great"

If you are trying to split the string at whitespace, it is a lot easier than you think.

String string = "Hello \t \t this\tis great";
String[] splitedString = string.split("\\s+"); // Split at every instance of multiple whitespace in a row.

If you want to split only at multiple tabs/spaces:

String[] splitedString = string.split("[\\t ]+");

If you really need to use StringTokenizer, which should never ever be used in the present time,...

StringTokenizer uselessTokenizer = new StringTokenizer(string, "[\\t ]+");

StringTokenizer("Hello \\t \\t this\\tis great") will construct an Enumeration from which you can extract the substrings you're looking for.

However, I can't imagine why you would want to do this, considering that "Hello \\t \\t this\\tis great".split("\\\\s") will do the same thing but return a String[] , which is much more useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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