Reputation: 3138
I'm trying to understand what is the proper way to achieve the following goal. Consider the following string:
/some/path/to/some/dir
I would like to split the path by /
and get the last two string and connect them with _
so the output would be:
some_dir
I'm familiar with the split function but I'm not sure what is the proper way to write this code when speaking of code-styling.
I know that I have to check first if the string is valid. For example, the string dir
is not valid.
What is the proper way to solve it?
Upvotes: 0
Views: 62
Reputation: 15028
If you're actually handling paths, you probably want to use the standard library's Path
ecosystem. You can use it by
Path path = Paths.get(p);
int nameCount = path.getNameCount();
if (nameCount < 2) throw new RuntimeException();
String result = String.format("%s_%s", path.getName(nameCount-2), path.getName(nameCount-1));
See it here.
The advantage is that when you're working on Windows, it will also handle the different path separator, so it's more platform independent.
The question of "dir" being "invalid" raises the follow-up question of how you want it handled. Throwing a RuntimeException
like I do is probably not going to hold up.
Upvotes: 0
Reputation: 939
You can use the below shown function for this purpose:
public String convertPath(String path) {
String[] str = path.split("/");
int length = str.length;
if(length < 2) {
//Customize the result here for this specific case
return "";
}
return str[length-2] + "_" + str[length-1];
}
Upvotes: 0
Reputation: 20951
You can play with the following. I omit error checks for the sake of simplicity.
class Test {
public static void main(String[] args) {
String s = "/some/path/to/some/dir";
String[] parts = s.split("/");
int len = parts.length;
String theLastTwoParts = parts[len - 2] + "_" + parts[len - 1];
System.out.println(theLastTwoParts);
}
}
Upvotes: 2