[英]How Do I Split A String With A Character That Has Multiples of the Same Character?
我正在尝试以一种可能不常见的方式解析字符串。 我在网上的任何地方都找不到答案。 该字符串涉及上传图片在ImageView中的目录路径。 目录字符串中有多个“/”字符。 如何告诉应用程序查看字符串中的最后一个“/”字符? 这是一个例子......
ImageView中上传图片的目录位置...
/storage/emulated/0/My Pictures/My family photo.png
我想拆分该字符串以仅显示My family photo
。 我要删除的文件夹和点扩展名。 只应显示文件名。
我试过这个...
String s = getAbsolutePath; //This contains the full string location in my example above.
String[] split1 = s.split("/");
String newS = split1[1];
String[] split2 = newS.split(".png");
String titleString = split2[0];
titleString
现在应该包含这个数据字符串My family photo 。
但是结果 output 实际上是storage
那么现在,我该如何编写代码来告诉应用程序查看文件名之前字符串中的最后一个/
呢?
感谢您的帮助! 非常感谢!!!
最简单的方法:
String path = "/storage/emulated/0/My Pictures/My family photo.png";
System.out.println(Paths.get(path).toFile().getName().replace(".png", ""));
此外,我建议发现 package java.nio.*
如果您正在处理文件系统,那么会有很多有用的收费。
您可以使用正则表达式执行此操作:
String path = "/storage/emulated/0/My Pictures/My family photo.png";
String filename = path.replaceAll(".*/(.*)\\.png","$1");
第一次拆分后,您将获得一个包含以下元素的数组:
{"", "storage", "emulated", "0", "My Pictures", "My family photo.png"}
因此,在您编写split1[1]
的第三行中,您将获得上述数组的第二个元素,即storage
。 在您的情况下,您想要获取最后一个元素。 因此,将您的代码更改为:
String s = getAbsolutePath; //This contains the full string location in my example above.
String[] split1 = s.split("/");
String newS = split1[split1.length - 1];
String[] split2 = newS.split(".png");
String titleString = split2[0];
split1.length - 1
是数组中最后一个元素的索引,即My family photo.png
结果是“我的全家福”
String x = "/storage/emulated/0/My Pictures/My family photo.png";
int index = x.lastIndexOf("/") + 1 ;
x = x.substring(index , x.lastIndexOf("."));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.