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);

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章