返回列表 發帖

indexOf() 與 lastIndexOf() 函式

本帖最後由 tonyh 於 2013-7-27 16:38 編輯
  1. //字元或字串位置, indexOf() 與 lastIndexOf() 函式
  2. public class ch70
  3. {
  4.     public static void main(String args[])
  5.     {
  6.         String str1="An apple a day keeps the doctor away!";
  7.         String str2="apple";
  8.         String str3="banana";
  9.         System.out.println("字串: "+str1);
  10.         System.out.println("第一個p出現在字串裡的第"+str1.indexOf("p")+"個位置");
  11.         System.out.println("最後一個s出現在字串裡的第"+str1.lastIndexOf("s")+"個位置");
  12.         System.out.println("自第8個位置往後找, 第一個a出現在字串裡的第"+str1.indexOf("a",8)+"個位置");
  13.         System.out.println("自第8個位置往後找, 最後一個a出現在字串裡的第"+str1.lastIndexOf("a",8)+"個位置");
  14.         if(str1.indexOf(str2)<0)     //若找不到, indexOf()函式的回傳值為-1
  15.             System.out.println("字串裡找不到"+str2);
  16.         else
  17.             System.out.println("字串裡有"+str2+", 出現在第"+str1.indexOf(str2)+"個位置");
  18.         if(str1.indexOf(str3)<0)
  19.             System.out.println("字串裡找不到"+str3);
  20.         else
  21.             System.out.println("字串裡有"+str3+", 出現在第"+str1.indexOf(str3)+"個位置");
  22.     }
  23. }
複製代碼

返回列表