Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get the text before and after the "-" (dash)

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
like image 826
HeartlessArchangel Avatar asked Dec 27 '11 15:12

HeartlessArchangel


4 Answers

With no error-checking or safety, this could work:

String[] parts = theString.split("-");
String first = parts[0];
String second = parts[1];
like image 99
josh.trow Avatar answered Oct 08 '22 20:10

josh.trow


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!

like image 37
mre Avatar answered Oct 08 '22 20:10

mre


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.

like image 21
JB Nizet Avatar answered Oct 08 '22 20:10

JB Nizet


    @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

like image 20
Alfredo Osorio Avatar answered Oct 08 '22 18:10

Alfredo Osorio