The task is to write a function that receives two portions of a path and joins them. The portions will be joined with the "/" separator. There could be only one separator and if it is not present it should be added.
Example:
joinPath("portion1", "portion2") ➞ "portion1/portion2"
joinPath("portion1/", "portion2") ➞ "portion1/portion2"
joinPath("portion1", "/portion2") ➞ "portion1/portion2"
joinPath("portion1/", "/portion2") ➞ "portion1/portion2"
My code:
public class Challenge {
public static String joinPath(String portion1, String portion2) {
return (portion1.substring(portion1.length()-1) != "/" && portion2.substring(0,1) != "/")
? portion1 + "/" + portion2 :
(portion1.substring(portion1.length()-1) == "/" && portion2.substring(0,1) == "/")
? portion1.substring(0) + portion2.substring(1) :
portion1 + portion2;
}
}
I know the code seems complex but the demand of the question was to try to solve it without if-else
conditions. I don't know why my code is failing almost all the tests.
I think I made a silly mistake. Can someone please point out the error? Also, is there a better way I can solve this question without using if-else
conditions?