Java中indexOf的用法--博客园

indexOf有四种用法:

1.indexOf(int ch) 在给定字符串中查找字符(ASCII),找到返回字符数组所对应的下标找不到返回-1

2.indexOf(String str)在给定符串中查找另一个字符串。。。

3.indexOf(int ch,int fromIndex)从指定的下标开始查找某个字符,查找到返回下标,查找不到返回-1

4.indexOf(String str,int fromIndex)从指定的下标开始查找某个字符串。。。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

public class Test {

    public static void main(String[] args) {

        char[] ch= {'a','b','c','h','e','l','l','o'};

        String str=new String(ch);

        //1.indexOf(int ch)

        str.indexOf(104);

        System.out.println(str.indexOf(104));//h所在下标为3

        //2.indexOf(String str)

        str.indexOf("hell");

        System.out.println(str.indexOf("hell"));//3

        //3.indexOf(int ch,int fromIndex)

        str.indexOf(1014);//4

        System.out.println(str.indexOf(1014));

        str.indexOf(101,5);//没有查找到返回-1

        System.out.println(str.indexOf(101,5));

        //4.indexOf(String str,int fromIndex)

        str.indexOf("che"0);//等价于str.indexOf("che")

        System.out.println(str.indexOf("che"0));//2

    }

}

  来源:https://www.cnblogs.com/xiaoke111/p/7660707.html

猜你喜欢

转载自blog.csdn.net/qq_42058441/article/details/85098039