我有一个StringBuilder,用于简单地反转并返回一个字符串。有问题的字符串是一个文件名:" server_1.8.2_java_8.jar" (这会有所不同)。
当我扭转字符串并将其返回时,它变为" sre _.._ aa8jra._vj281rve"。我已经使用了一些变体(以及常规句子,如"反转此字符串")我得到相同的结果。
但是,如果我直接在方法内部分配字符串(而不是将其作为参数并在其上执行some operations),它似乎正常工作。
测试方法代码以防有害:
static String parseJarfileName(String jarLocation) {
if(jarLocation == null)
return ""; // path to jar location is empty,
// return so stuff doesn't get messed up
String jarfileName = ""; // name of the .jar server executable
for(int i = jarLocation.length(); jarLocation.charAt(i - 1) != '/'; i --) {
// read the string backwards until a / is found,
// signaling that the jarfile name has ended
// as this is done, concatenate the characters of the jarfile name
jarfileName += jarLocation.charAt(i - 1);
jarfileName.trim();
// the jarfile name will be backwards here, so reverse it
String str = new StringBuilder(jarfileName).reverse().toString();
jarfileName = str;
}
return jarfileName;
}
public static void main(String[] args) {
String filePath = "/Users/John/Desktop/server/server_1.8.2_java_8.jar";
String fileName = parseJarfileName(filePath);
System.out.println(fileName);
}
// written by 2xedo: twitter.com/2xedo
此代码打印" sre _.._ aa8jra._vj281rve"到控制台。
答案 0 :(得分:4)
如果我没弄错的话,你正在寻找像
这样的东西public static String parseJarfileName(String jarLocation) {
if (jarLocation == null)
return "";
return jarLocation.substring(jarLocation.lastIndexOf('/')+1);
}
或者可能更具可读性
public static String parseJarfileName(String jarLocation) {
if (jarLocation == null)
return "";
return new File(jarLocation).getName();
}
您还可以使用Path
File
return Paths.get(jarLocation).getFileName().toString();
答案 1 :(得分:2)
如果您要做的只是返回文件名,为什么不做jarLocation.substring(jarLocation.lastIndexOf("/") + 1, jarLocation.length);
你可能还需要做更多的事情来处理边缘情况等等,但这应该能为你提供你正在寻找的东西。
答案 2 :(得分:1)
每次迭代都会反转文件名。
r
ra
arj
jra.
.arj8
//...
在reverse()
循环结束后移动for
代码。
} // end of for loop
// the jarfile name will be backwards here, so reverse it
String str = new StringBuilder(jarfileName).reverse().toString();
jarfileName = str;
return jarfileName;
}
此外,在没有空格的文件名中似乎并不重要,但
jarfileName.trim();
如果没有将返回值赋给某个东西,就没用了。使用
jarfileName = jarfileName.trim();
答案 3 :(得分:0)
您可以删除此内容:
String str = new StringBuilder(jarfileName).reverse().toString();
jarfileName = str;
一切似乎都很好。