java字符串截取--截取倒数第二个指定字符之前/后的字符串

截取倒数第二个"/"之前的字符串

	String path="/home/henry/Desktop/1.txt";
	
	//获得""/home/henry",并且不需要前面的"/"
    String oo=path.substring(0,path.lastIndexOf("/",path.lastIndexOf("/")-1));
    //"-1"代表在定位时往前取一位,即去掉"/"
    //从path.lastIndexOf("/")-1位置开始向前寻找倒数第二个"/"的位置
    //最后用substring()方法来进行截取
    System.out.println(oo);

截取倒数第二个"/"之后的字符串

	String path="/home/henry/Desktop/1.txt";
	
	//获得"Desktop/1.txt",并且不需要前面的"/"
    String oo=path.substring(path.lastIndexOf("/",path.lastIndexOf("/")-1)+1);
    //"+1"代表在定位时往后取一位,即去掉"/"
    //"-1"代表以"/"字符定位的位置向前取一位
    //从path.lastIndexOf("/")-1位置开始向前寻找倒数第二个"/"的位置
    
    System.out.println(oo);

在这里插入图片描述

发布了81 篇原创文章 · 获赞 44 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/daponi/article/details/102985742