substring常用方法和lastIndexOf方法
阿新 • • 發佈:2021-01-28
技術標籤:java基礎
1、 substring常用的兩種方法
msg.substring(0,3):表示取前三個字元;
msg.substring(5):表示去掉前五個字元,返回一個新的字串(只包含去掉前五個字元後剩下的字串)
程式碼:
package com.sddm;
public class Demo01 {
public static void main(String[] args) {
String msg = "/hello/world/123";
//表示從第一個字元開始擷取,擷取前三個
String str1 = msg.substring(0, 3);
System.out.println("msg.sbustring(0,3):"+str1);
//表示去掉前五個字元,保留之後字元
String str2 = msg.substring(5);
System.out.println("msg.sbustring(5):"+str2);
}
}
結果截圖:
2、 lastIndexOf用法
表示獲取該字元在字串中最後出現的位置從0開始計算
程式碼:
public class Demo01 {
public static void main(String[] args) {
String msg = "/hello/world/123";
//獲取最後出現/的索引
System.out.println(msg.lastIndexOf("/"));
//獲取從第一個字元到/前個一個字元
String str3 = msg.substring(0,msg.lastIndexOf("/"));
System.out.println("msg.sbustring(5):" +str3);
}
}
截圖: