String类之indexOf--->查找某字对应的位置

以下方法都是java内置类String类的内置方法(不是构造方法哦,就是普通的方法),不需要我们写,直接拿过来用即可。

  • indexOf方法对应Api介绍
  • lastIndexOf方法对应Api介绍

 --------------indexOf方法对应Api介绍-----------------------

 

字符/char的查找

indexOf查找某个字符在字符串中的文字:indexOf(int ch)

public class Demo {
    public static void main(String[] args)  {
        String Str="MyNameIsDsh";
        int location=Str.indexOf("D");
        System.out.println("您查询的关键字位置:"+location);
    }
}

您查询的关键字位置:8

 

如果您不嫌麻烦,可以按照Api介绍的写,不过几乎一样,但代码还多

public class Demo {
    public static void main(String[] args)  {
        String Str="MyNameIsDsh";
        char key='D';
        int location=Str.indexOf(key);
        System.out.println("您查询的关键字位置:"+location);
    }
}

您查询的关键字位置:8

 

 

indexOf查找某个字符在字符串中的文字。从指定位置查找,首次查找到关键字后,便终止继续查找:indexOf(int ch, int fromIdex)

public class Demo {
    public static void main(String[] args)  {
        String Str="Hello,joe.ok";
        
        //说明:从起始位置开始,直到碰到关键字"o",输出首次出现位置后并终止搜索
        System.out.println("您查询的关键字位置:"+Str.indexOf("o"));//不写搜索起始位置,默认起始位置为1
        System.out.println("您查询的关键字位置:"+Str.indexOf("o",5));//搜索起始位置为5
        System.out.println("您查询的关键字位置:"+Str.indexOf("o",8));//搜索起始位置为8
    }
}

您查询的关键字位置:4
您查询的关键字位置:7
您查询的关键字位置:10

 

 

字符串/String的查找

indexOf查找某个字符串在字符串中的文字,:indexOf(String str)

public class Demo {
    public static void main(String[] args)  {
        String Str="Hello,joe.Why are your name is joe";
        String Child_Str="joe";
        int location=Str.indexOf(Child_Str);//其实不写搜索起始位置,默认起始位置为1,和后边写1效果一样
        
        System.out.println("您查询的关键字位置:"+location);
    }
}

您查询的关键字位置:6

 

 

indexOf查找某个字符串在字符串中的文字,从指定位置查找,首次查找到关键字后,便终止继续查找:indexOf(String str, int fromIdex)

public class Demo {
    public static void main(String[] args)  {
        String Str="Hello,joe.Why are your name is joe";
        String Child_Str="joe";
        
        System.out.println("您查询的关键字位置:"+Str.indexOf(Child_Str,1));
        System.out.println("您查询的关键字位置:"+Str.indexOf(Child_Str,7));
    }
}

您查询的关键字位置:6
您查询的关键字位置:31

 

 

---------------lastIndexOf方法对应Api介绍--------------------

public class Demo {
    public static void main(String[] args)  {
        String Str="Hello,joe.Why are your name is joe";
        String Child_Str="joe";
        
        //说明:用法和indexOf一样,只是功能有些不一样
        System.out.println("您查询的关键字位置:"+Str.lastIndexOf("o"));// 【查找字符】返回指定字符在此字符串中最后一次(也就是最右边)出现处的索引。
        System.out.println("您查询的关键字位置:"+Str.lastIndexOf("o",31));// 【查找字符】返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
        System.out.println("您查询的关键字位置:"+Str.lastIndexOf(Child_Str));//【查找字符串】返回指定子字符串在此字符串中最后一次(也就是最右边)出现处的索引,
        System.out.println("您查询的关键字位置:"+Str.lastIndexOf(Child_Str,29));//【查找字符串】返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
    }
}

您查询的关键字位置:32
您查询的关键字位置:19
您查询的关键字位置:31
您查询的关键字位置:6

 

---------如果没有查到则会输出-1,但不会报异常--------------

posted @ 2016-01-03 17:19  丁少华  阅读(9320)  评论(0编辑  收藏  举报