java lastIndexOf以及substring 方法笔记

开发了很久,到操作String的时候仍然没有把握使用这两个方法。所以写一个笔记就当加深印象。

例如现在想取得目录的最后一级的目录名。目录名如下:
“program/visit/lol” 现在想拿到”lol”,应该怎样做呢。

接下来是测试代码:

public class Test{
    public static void main(String[] args) {
        String s = "program/visit/lol";
        String lol = s.substring(s.lastIndexOf("/")+1);
        String lol2 = s.substring(s.lastIndexOf("/")+1,s.length());
        System.out.println("");
        System.out.println(s.lastIndexOf("/"));
        System.out.println("");
        System.out.println(lol);
        System.out.println("");
        System.out.println(lol2);
    }
}

可以得到如下的结果:

13

lol

lol

由此可见

  • String 的 index是从0 开始的,lastIndexOf取的是最后一个匹配字符的index值。
  • 带有一个参数的substring方法会返回包含索引值以及它之后所有字符的子字符。
  • 带有两个参数的substring方法会返回包含第一个参数作为索引值,到第二个参数作为索引值的字符的前一个字符的子字符。

总结:获取文件扩展名的写法为:

String surfix = s.substring(s.lastIndexOf(".")+1);

补充:
获取最后一个符号之前所有字符的方式:

String fileName = s.substring(0,s.lastIndexOf("."));

猜你喜欢

转载自blog.csdn.net/thezprogram/article/details/78413570