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.
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.
CodePudding user response:
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;
}