String Tokenizer, delimiter

早过忘川 提交于 2019-12-12 22:29:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!