Divide a string into two at hyphen

2020-07-21 03:33发布

问题:

I am taking a String variable from request.

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

This may or may not have a hyphen in the middle. I want to be able to traverse through the String and divide the string when hyphen is seen.

回答1:

Use String#split:

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

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



回答2:

String.split



回答3:

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.



回答4:

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