Hea*_*gel 13 java string android split
我有一个字符串,我想得到" - "(破折号)之前和之后的单词.我怎样才能做到这一点?
示例:字符串:
"First part - Second part"
Run Code Online (Sandbox Code Playgroud)
输出:
first: First part
second: Second part
Run Code Online (Sandbox Code Playgroud)
jos*_*row 24
没有错误检查或安全性,这可能有效:
String[] parts = theString.split("-");
String first = parts[0];
String second = parts[1];
Run Code Online (Sandbox Code Playgroud)
mre*_*mre 11
简单:使用String.split
方法.
示例:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
final String after = s.split("-")[1]; // "After"
Run Code Online (Sandbox Code Playgroud)
请注意,我正在为您保留错误检查和空白区域修剪!
int indexOfDash = s.indexOf('-');
String before = s.substring(0, indexOfDash);
String after = s.substring(indexOfDash + 1);
Run Code Online (Sandbox Code Playgroud)
阅读javadoc有助于找到这些问题的答案.