对于字符串的处理,真的是每个人的写法都不同。
今天做了一个文件查找的功能,就遇到了对字符串的处理。
文件查找的格式通常是这样的:"/目录1/目录2/目录3"
当我要返回上一个目录的时候,就得对字符串进行处理。
我最开始的想法是,当点击返回上一个目录时,把当前目录的路径名用split("/")来切割成多个文件夹名,然后把除了最后一个文件夹名的其他拼接起来,成为新的目录的路径名。
String current_path = "/目录1/目录2/目录3";
String[] filename = current_path.split("/");
这样切割出来的字符串数组就有4个了:"",“目录1”,“目录2”,“目录3”。
我们去掉第一个空字符串和最后一个目录3,用"/“拼接剩下的得到需要的新的路径名”/目录1/目录2"。
String current_path = "/目录1/目录2/目录3";
String[] filename = current_path.split("/");
current_path = "";//初始化当前路径名
if (str.length > 2) {
for (int i = 1; i < str.length - 1; i++) {
current_path += "/" + str[i];
}
}
if (current_path.equals("")) {//当前路径为根目录
current_path = "/";
}
这样又是切割又是拼接的,绕来绕去终于写完了,在本地目录上跳转也没问题了。
但是,写完后突然想到,搞这么麻烦为什么不直接用substring呢?
然后我又删掉重写了。
String current_path = "/目录1/目录2/目录3";
String[] filename = current_path.split("/");
//当前路径长度 - 最后一个文件名长度 - "/"的长度
int endIndex = current_path.length()-str[str.length-1].length()-1;
current_path = current_path.substring(0,endIndex);
if (current_path.equals("")) {//当前路径为根目录
current_path = "/";
}
这样看起来终于舒服点了。