public class Demo {
public static void main(String[] args) {
File file = new File("aaa.png");
String name = file.getName();
String s = name.substring(name.lastIndexOf("."));
String sub = name.substring(name.lastIndexOf(".") + 1);
System.out.println(name);
System.out.println(s);
System.out.println(sub);
}
}
控制台打印
aaa.png
.png
png
String . lastIndexOf(".") 从字符串最后出现 . 的地方截取
包括 . 在内
即 . 为 索引 0开始截取
此用法 常用于 获取 文件的格式
#######
在后面使用过程中
public class SubstringTest {
public static void main(String[] args) {
String path="111.222.333.444";
String substring = path.substring(0, path.lastIndexOf("."));
System.out.println(substring);//111.222.333
String substring1 = path.substring(path.indexOf("."));
System.out.println(substring1);//.222.333.444
String substring2 = path.substring(path.indexOf("."),path.lastIndexOf("."));
System.out.println(substring2);//.222.333
}
}
规律是 [左边, 右边) 类似区间的效果,左边包含,右边不包含