开发者

string cutting challenge to get one dir level up efficently

开发者 https://www.devze.com 2023-01-05 00:59 出处:网络
what is the most efficient way to get one directory tree level up ? i am looking for most efficient use of string class meth开发者_运维技巧od to

what is the most efficient way to get one directory tree level up ? i am looking for most efficient use of string class meth开发者_运维技巧od to getting e:\files\report\fruits from e:\files\report\fruits\apples


I think you are better off just using

File f = new File("e:\\files\\report\\fruits\\apples");
String parent = f.getParent();

If you insist on using String only and assuming '\' is the path separator, you can do something like this:

String s = "e:\\files\\report\\fruits\\apples";
String parent = s.substring(0, s.lastIndexOf('\\'));

But you have to beware of edge cases like there being no character '\' found.


I wouldn't do this by "string bashing" because it will embed all sorts of platform dependencies on pathname syntax into your code. Instead, use the java.io.File class.

String parent = new File("e:\files\report\fruits\apples").getParent();

or better still:

File parent = new File("e:\files\report\fruits\apples").getParentFile();


Stephen makes a valid point about platform dependency, but here's what you asked for:

String dir = "e:\\files\\report\\fruits\\apples";
String parent = dir.replaceAll("\\\\[^\\\\]+$", "");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号