0

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?

coderfromhell
  • 435
  • 1
  • 4
  • 13

2 Answers2

3

How about this:

static String joinPath(String path1, String path2)
{
    return String.format("%s/%s", path1, path2).replaceAll("/+", "/");
}

We insert a "/" between whatever paths we're given, then collapse strings of one or more "/"s to a single "/".

Test:

portion1 portion2 : portion1/portion2
portion1/ portion2 : portion1/portion2
portion1 /portion2 : portion1/portion2
portion1/ /portion2 : portion1/portion2
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16
2
public class Challenge {
public static String joinPath(String portion1, String portion2) {
   return portion1.replace("/","") + "/" + portion2.replace("/","");
 }
}
Nikhil
  • 1,126
  • 12
  • 26