Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to splitting different special characters in Java with using if contains?

I have “-“ characters in my strings as below.
I am using if contains “-“ and splitting correctly. But some string values are also “-“ characters in different indexes.
I tried to use 2nd if contains “.-“ cannot solve the issue as well.
So have can I get correct outputs without “-“ characters perfectly?

13-adana-demirspor -> has 2 “-“ characters.

15-y.-malatyaspor -> has “-“ characters too.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1st and 2nd strings makes problem for splitting.

And others has only one “-“ character and no issue.

My Code is:

final String [] URL  = {
            "13-adana-demirspor",
            "14-fenerbahce",
            "15-y.-malatyaspor",
            "16-trabzonspor",
            "17-sivasspor",
            "18-konyaspor",
            "19-giresunspor",        
            "20-galatasaray"
          };

        for(int i=0; i<URL.length; i++)

        String team;

    if (URL[i].contains("-")) {
        String[] divide = URL[i].split("-");
        team = divide[1];
        System.out.println("     " + team.toUpperCase());

    } else if (URL[i].contains(".-")){
        String[] divide = URL[i].split(".-");
        team = divide[2];
        System.out.println("     " + team.toUpperCase());

    }else {
        team = null;
    }

My Output is:

ADANA ** missing second word

FENERBAHCE

Y. ** missing second word

TRABZONSPOR

SIVASSPOR

KONYASPOR

GIRESUNSPOR

GALATASARAY

Thanks for your help.

>Solution :

it looks like you just want to split on the first occurence. for this you can use the second parameter of split and set that to 2. So like

if (URL[i].contains("-")) {
    String[] divide = URL[i].split("-", 2);
    team = divide[1];
    System.out.println("     " + team.toUpperCase());
} else {
    team = null;
}

to get the last part instead you could do

if (URL[i].contains("-")) {
    String[] divide = URL[i].split("-");
    team = divide[divide.length - 1];
    System.out.println("     " + team.toUpperCase());
} else {
    team = null;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading