问题
I am using this code:
StringTokenizer tokenizer=new StringTokenizer(line, "::");
to split the following String:
hi my name is visghal:: what is yor name name:: being thw simple my::: what is yor name name.
Now i want to split the string using ::
as delimiter. It is working fine. But it is also taking :::
into consideration.
In other words i want:
hi my name is visghal
what is yor name name
being thw simple my
: what is yor name name
Instead it is giving me the following:
being thw simple my
what is yor name name
hi my name is visghal
It is taking ::
and :::
as same. Is there any means to avoid this?
回答1:
You can just use String#split like this:
String[] arr = str.split("::");
EDIT:
String[] arr = str.split("::\\s*"); // for stripping spaces after ::
OUTPUT:
hi my name is visghal
what is yor name name
being thw simple my
: what is yor name name
回答2:
Try Guava's Splitter if you need additional functionality over String.split
. It will allow for trimming and omitting empty strings.
String myInput = "...";
Iterable<String> parts = Splitter.on("::").split(myInput);
回答3:
It is taking :: and ::: as same
No, your delimeter ::
is found twice in this string part :::
and this is the explanation for your result.
You should use split("::")
method.
来源:https://stackoverflow.com/questions/13066929/string-tokenizer-delimiter