开发者

Divide a string into two at hyphen

I am taking a String variable from request.

String issueField = request.getParameter("issueno");

This may or may not have a hyph开发者_如何学JAVAen in the middle. I want to be able to traverse through the String and divide the string when hyphen is seen.


Use String#split:

String[] parts = issueField.split("-");

Then you can use parts[0] to get the first part, parts[1] for the second, ...


String.split


Although String.split will do the job, Guava's Splitter class doesn't silently discard trailing separators, and it's API doesn't force using a regex when it's not needed:

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Splitter.html

With respect to your question, here's a code snippet:

Iterable<String> parts = Splitter.on('-').split(issueField);

Some additional bonuses with using Splitter instead of String.split:

  • The returned Iterable is lazy. In other words, it won't actually do the work until you are iterating over it.
  • It doesn't split all of the tokens and store them in memory. You can iterate over a huge string, token-by-token, w/o doubling up on memory usage.

The only reason not to use Splitter is if you don't want to include Guava in your classpath.


You can use java.util.StringTokenizer class as well. Though String.split is more easy and suitable way for your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜