Java中字串中子串的尋找共有四種方法(indexof())

來源:互聯網
上載者:User

標籤:dex   結果   test   static   print   nbsp   rda   code   沒有   

indexOf 方法返回一個整數值,指出 String 對象內子字串的開始位置。如果沒有找到子字串,則返回-1。
如果 startindex 是負數,則 startindex 被當作零。如果它比最大的字元位置索引還大,則它被當作最大的可能索引。

Java中字串中子串的尋找共有四種方法,如下:
1、int indexOf(String str) :返回第一次出現的指定子字串在此字串中的索引。 
2、int indexOf(String str, int startIndex):從指定的索引處開始,返回第一次出現的指定子字串在此字串中的索引。 
3、int lastIndexOf(String str) :返回在此字串中最右邊出現的指定子字串的索引。 
4、int lastIndexOf(String str, int startIndex) :從指定的索引處開始向後搜尋,返回在此字串中最後一次出現的指定子字串的索引。

 

public class Test {      public static void main(String[] args) {          String s = "xXccxxxXX";          // 從頭開始尋找是否存在指定的字元         //結果如下           System.out.println(s.indexOf("c"));     //2          // 從第四個字元位置開始往後繼續尋找,包含當前位置          System.out.println(s.indexOf("c", 3));  //3          //若指定字串中沒有該字元則系統返回-1          System.out.println(s.indexOf("y"));     //-1          System.out.println(s.lastIndexOf("x")); //6      }  }

 

private static void testIndexOf() {      String string = "aaa456ac";        //尋找指定字元是在字串中的下標。在則返回所在字串下標;不在則返回-1.      System.out.println(string.indexOf("b"));//indexOf(String str);返回結果:-1,"b"不存在        // 從第四個字元位置開始往後繼續尋找,包含當前位置      System.out.println(string.indexOf("a",3));//indexOf(String str, int fromIndex);返回結果:6        //(與之前的差別:上面的參數是 String 類型,下面的參數是 int 類型)參考資料:a-97,b-98,c-99        // 從頭開始尋找是否存在指定的字元      System.out.println(string.indexOf(99));//indexOf(int ch);返回結果:7      System.out.println(string.indexOf(‘c‘));//indexOf(int ch);返回結果:7        //從fromIndex尋找ch,這個是字元型變數,不是字串。字元a對應的數字就是97。      System.out.println(string.indexOf(97,3));//indexOf(int ch, int fromIndex);返回結果:6      System.out.println(string.indexOf(‘a‘,3));//indexOf(int ch, int fromIndex);返回結果:6        //這個就是靈活運用String類提供的方法,拆分提供的字串。      //String s = "D:\\Android\\sdk\\add-ons";      //System.out.println(s);      //while (s.lastIndexOf("\\") > 0) {      //    s = s.substring(0, s.lastIndexOf("\\"));      //    System.out.println(s);      //}  }

 

 

Java中字串中子串的尋找共有四種方法(indexof())

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.