Java中字串indexof() 的使用方法

來源:互聯網
上載者:User

標籤:div   使用方法   xxxxx   str   span   指定   word   []   tar   

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) :從指定的索引處開始向後搜尋,返回在此字串中最後一次出現的指定子字串的索引。

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

雖然簡單,我就做個筆記。

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.