I have a String and I want to get the words before and after the " - " (dash). How can I do that?
example: String:
"First part - Second part"
output:
first: First part
second: Second part
With no error-checking or safety, this could work:
String[] parts = theString.split("-");
String first = parts[0];
String second = parts[1];
Easy: use the String.split
method.
Example :
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
final String after = s.split("-")[1]; // "After"
Note that I'm leaving error-checking and white-space trimming up to you!
int indexOfDash = s.indexOf('-');
String before = s.substring(0, indexOfDash);
String after = s.substring(indexOfDash + 1);
Reading the javadoc helps finding answers to such questions.
@Test
public void testSplit() {
String str = "First part - Second part";
String strs[] = str.split("-");
for (String s : strs) {
System.out.println(s);
}
}
Output:
First part
Second part
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With