思路:想要根據(jù)某個特殊字符進(jìn)行截取字符串,最終是要用到substring()函數(shù),那么關(guān)鍵,是要找到特殊字符所在的位置,也就是要用到函數(shù)indexOf()和laseIndexOf()兩個函數(shù)。
舉例:
String str = "abc_def_ghi_jkl_mn";
?1.找到第一個“_”的位置。
int index = str.indexOf("_");
2.找到第二個“_”的位置。是在第一個“_”的基礎(chǔ)上尋找。
int index = str.indexOf("_", str.indexOf("_") + 1);
3.找到倒數(shù)第一個“_”的位置。
int index = str.lastIndexOf("_");
4.找到倒數(shù)第二個“_”的位置。在倒數(shù)第一個的基礎(chǔ)上尋找。
int index = str.lastIndexOf("_", str.lastIndexOf("_") - 1);
5.根據(jù)特殊字符位置,查詢前后的字符。
String res1 = str.substring(0, index);
String res2 = str.substring(index + 1);
Test:
public static void main(String[] args) {
String str = "abc_def_ghi_jkl_mn";
//截取第一個_之前/之后的字符
int oneIndex = str.indexOf("_");
System.out.println("第一個_的位置:" + oneIndex);
String res1 = str.substring(0, oneIndex);
System.out.println("第一個_之前的字符串:" + res1);
String res2 = str.substring(oneIndex + 1);
System.out.println("第一個_之后的字符串:" + res2);
//截取第二個_之前/之后的字符
int twoIndex = str.indexOf("_", str.indexOf("_") + 1);
System.out.println("第二個_的位置:" + twoIndex);
String res3 = str.substring(0, twoIndex);
System.out.println("第二個_之前的字符串:" + res3);
String res4 = str.substring(twoIndex + 1);
System.out.println("第二個_之后的字符串:" + res4);
//截取倒數(shù)第一個_之前/之后的字符
int lastOneIndex = str.lastIndexOf("_");
System.out.println("倒數(shù)第一個_的位置:" + lastOneIndex);
String res5 = str.substring(0, lastOneIndex);
System.out.println("倒數(shù)第一個_的之前的字符:" + res5);
String res6 = str.substring(lastOneIndex + 1);
System.out.println("倒數(shù)第一個_的之后的字符:" + res6);
//截取倒數(shù)第二個_之前/之后的字符
int lastTwoIndex = str.lastIndexOf("_", str.lastIndexOf("_") - 1);
System.out.println("倒數(shù)第二個_的位置:" + lastTwoIndex);
String res7 = str.substring(0, lastTwoIndex);
System.out.println("倒數(shù)第二個_的之前的字符:" + res7);
String res8 = str.substring(lastTwoIndex + 1);
System.out.println("倒數(shù)第二個_的之后的字符:" + res8);
}
文章來源:http://www.zghlxwxcb.cn/news/detail-514830.html
over!?文章來源地址http://www.zghlxwxcb.cn/news/detail-514830.html
到了這里,關(guān)于Java截取某個特殊字符前后的字符串的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!