Java字串尋找的三種方式,java字串三種方式

來源:互聯網
上載者:User

Java字串尋找的三種方式,java字串三種方式

indexof方法:

註解:indexOf 方法返回一個整數值,指出 String 對象內子字串的開始位置。如果沒有找到子字串,則返回-1。

public class IndexOf{public static void main(String[] args){String s="李宏#王海#林巧#陸尋#唐梅";String q="#"; //需要尋找的字串String err="*"; //不存在的字串int i=0;for(int j=0;j<s.length();j++){ //迴圈所有字串String get=s.substring(j,j+1); //列印所有字串if(get.equals(q)){ //判斷#字是否出現i++; //#字出現次數}}System.out.println("總共有"+s.length()+"個字串");System.out.println("#字共出現了"+i+"次"); //#字元總共出現的次數System.out.println("第一個#字出現在字串的"+s.indexOf(q)+"個位置"); if(s.indexOf(err)==-1){ //返回-1則表示字元不存在字串中System.out.println("*字在字串中不存在");}}}

運行結果:

總共有14個字串
#字共出現了4次
第一個#字出現在字串的2個位置
*字在字串中不存在

startsWith方法:

註解:startsWith() 方法用於檢測字串是否以指定的首碼開始。

public class StartWith{public static void main(String[] args){String id[]= {"53011198902280308","52011198711038269","53011197701328291"};int number = 0;System.out.println("合格字串有");for(int i=0;i<id.length;i++) {if(id[i].startsWith("530") == true) {number++;System.out.println(id[i]);}}System.out.println("前面3個字元為‘530'的身份證有:"+number+"個");}}

運行結果:

合格字串有
53011198902280308
53011197701328291
前面3個字元為‘530'的身份證有:2個

regionMatches方法:

註解:regionMatches() 方法用於檢測兩個字串在一個地區內是否相等。

public class RegionMatches{public static void main(String[] args) {int number = 0;String s = "student;entropy;ENgage,English,client,eye";String q="en"; //需要尋找的字串for (int k=0;k<s.length();k++){//true為不區分大小寫,k為所有字串,q為需要尋找的字串,0為從字串1的位置開始,2為需要尋找的字串長度為2if(s.regionMatches(true, k, q, 0, 2)){ number++;System.out.println("en字元在字串的第"+k+"個位置");}}System.out.println("含有‘en'子串的字串的總數有:"+number);}}

運行結果:

en字元在字串的第4個位置
en字元在字串的第8個位置
en字元在字串的第16個位置
en字元在字串的第23個位置
en字元在字串的第34個位置
含有‘en'子串的字串的總數有:5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.