1. 程式人生 > 其它 >java擷取字串筆記

java擷取字串筆記

//擷取_之前字串

public static void substringTest01() {
String str = "test_https://www.baidu.com/";
String str1 = str.substring(0, str.indexOf("_"));
System.out.println("擷取_之前字串:" + str1);
}


//擷取_之後字串

public static void substringTest02() {
String str = "test_https://www.baidu.com/";

String str1 = str.substring(0, str.indexOf("_"));
String str2 = str.substring(str1.length() + 1, str.length());
System.out.println("擷取_之後字串:" + str2);
}


//擷取第二個_之後字串

public static void substringTest03() {
String str = "0123456_89_sdfdsdsf_23423_auauauau";
//獲得第一個點的位置
int index = str.indexOf("_");

System.out.println("獲得第一個點的位置:" + index);
//根據第一個點的位置 獲得第二個點的位置
index = str.indexOf("_", index + 1);
System.out.println("根據第一個點的位置 獲得第二個點的位置:" + index);
//根據第二個點的位置,擷取 字串。得到結果 result
String result = str.substring(index + 1);
//輸出結果
System.out.println("輸出結果:" + result);
}


//擷取倒數第三個_之前的字串

public static void substringTest04() {
String b = "/dota-2/talent/arc-warden-20-2-38";
String subStringB = b.substring(b.lastIndexOf("/") + 1);
int index = subStringB.lastIndexOf("-");
index = subStringB.lastIndexOf("-", index - 1);
index = subStringB.lastIndexOf("-", index - 1);
System.out.println(subStringB.substring(0, index));
}