Split a string into two in a hyphen

I take the String variable from the request.

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

It may or may not have a hyphen in the middle. I want to be able to iterate through String and divide the string when a hyphen is displayed.

+3
source share
4 answers

Use String # split:

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

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

+9
source
+2
source

String.split , Guava Splitter , API , :

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

, :

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

Splitter String.split:

  • Return Iterablelazy. In other words, this will not actually work until you repeat it.
  • It does not break all tokens and store them in memory. You can iterate over a huge string, a token token, without doubling the memory usage.

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

+1
source

You can also use the java.util.StringTokenizer class. Although String.split is a simpler and more suitable way for your problem.

0
source

Source: https://habr.com/ru/post/1791411/


All Articles