Java 实例 - 字符串搜索


以下实例使用了 String 类的 indexOf() 方法在字符串中查找子字符串出现的位置,如过存在返回字符串出现的位置(第一位为0),如果不存在返回 -1:

  1. //SearchStringEmp.java 文件
  2.  
  3. public class SearchStringEmp{
  4. public static void main(String[] args) {
  5. String strOrig = "Hello readers";
  6. int intIndex = strOrig.indexOf("Hello");
  7. if(intIndex == - 1){
  8. System.out.println("Hello not found");
  9. }else{
  10. System.out.println("Found Hello at index "
  11. + intIndex);
  12. }
  13. }
  14. }

以上代码实例输出结果为:

  1. Found Hello at index 0