Java 實例 - 字符串搜索
以下實例使用了 String 類的 indexOf() 方法在字符串中查找子字符串出現的位置,如過存在返回字符串出現的位置(第一位為0),如果不存在返回 -1:
//SearchStringEmp.java 文件 public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1){ System.out.println("Hello not found"); }else{ System.out.println("Found Hello at index " + intIndex); } } }
以上代碼實例輸出結果為:
Found Hello at index 0