java 在连字符处将字符串一分为二

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4965966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:49:58  来源:igfitidea点击:

Divide a string into two at hyphen

javastringsubstring

提问by Some Java Guy

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.

这中间可能有也可能没有连字符。我希望能够遍历字符串并在看到连字符时分割字符串。

回答by Chris Kuehl

Use String#split:

使用字符串#split:

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

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

然后你可以使用parts[0]来获取第一部分,parts[1]对于第二部分,......

回答by Eldad Mor

回答by enonu

Although String.splitwill 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:

尽管String.split可以完成这项工作,但 Guava 的 Splitter 类不会默默地丢弃尾随分隔符,并且它的 API 在不需要时不会强制使用正则表达式:

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

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:

使用 Splitter 而不是 String.split 的一些额外好处:

  • The returned Iterableis 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.
  • 返回Iterable是懒惰的。换句话说,在您对其进行迭代之前,它实际上不会完成工作。
  • 它不会拆分所有令牌并将它们存储在内存中。您可以逐个标记地迭代一个巨大的字符串,而不会使内存使用量增加一倍。

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

不使用 Splitter 的唯一原因是如果您不想在类路径中包含 Guava。

回答by Garbage

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

您也可以使用 java.util.StringTokenizer 类。虽然 String.split 更容易和更适合您的问题。