Java中根據特定字符截取字符串的方法


1、String的substring()方法:根據索引截取

  //截取從下標begin到str.length()-1內容
  substring(begin) 
  //截取指定范圍的內容
  substring(begin,end)

舉個栗子:

  
  String str = "abc_def_Ghi";   //索引0~10

  //截取以下標2元素開始余下的字符
  System.out.println(str.substring(1));    //bc_def_Ghi(含1的位置)

  //從下標為3的位置開始截取,到5個位置停止截取,結果不包括5
  System.out.println(str.substring(3,5));  //_d

2、String的indexof():返回一個整數值,即索引位置

        String s = "abc_def_Ghi";//0~10
        // int indexOf(String str) :返回第一次出現的指定子字符串在此字符串中的索引。        
        //從頭開始查找是否存在指定的字符
        System.out.println(s.indexOf("c"));     //2
        //int indexOf(String str, int startIndex):從指定的索引處開始,返回第一次出現的指定子字符串在此字符串中的索引。
        // 從索引為3位置開始往后查找,包含3的位置
        System.out.println(s.indexOf("d", 3));  //4
        //若指定字符串中沒有該字符則系統返回-1
        System.out.println(s.indexOf("A"));     //-1
        //int lastIndexOf(String str) 從后往前找一次出現的位置
        System.out.println(s.lastIndexOf("_")); //7

靈活運用這兩個方法,可以進行多樣的操作

(1)獲取第一個"_"及后面所有字符,舉例:

String a = "abc_def_Ghi";
int index = a.indexOf("_");//獲取第一個"_"的位置3
String str1 = a.substring(index);//含"_"
System.out.println("第一個_及后面字符串為:" + str1);//_def_Ghi

(2)獲取第一個"_"前面所有字符,舉例:

String a = "abc_def_Ghi";
int index = a.indexOf("_");//獲取第一個"_"的位置3
String str2 = a.substring(0,index);//不含"_",這叫含頭不含尾
System.out.println("第一個_前面字符串為:" + str2 );//abc

(3)獲取第二個"_"及后面所有字符,舉例:

String a = "abc_def_Ghi";
String str3 = a.substring(a.indexOf("_",a.indexOf("_") + 1));//包含本身位置
System.out.println("第二個_及后面字符串為:" + str3 );//_Ghi

(4)獲取第二個"_"前面所有字符,舉例:

String a = "abc_def_Ghi";
String str4 = a.substring(0,a.indexOf("_",a.indexOf("_") + 1));//不包含本身位置
System.out.println("第二個_前面字符串為:" + str4 );//abc_def

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM