java indexOf()方法

java indexOf()方法

indexOf()方法,属于 String类 中的方法。

indexOF()方法,有四种形式的用法:

  • public int indexOf(int ch)  返回指定字符ch在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回-1。
  • public int indexOf(int ch,int fromIndex) 返回从fromIndex位置开始查找指定字符ch在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回-1。
  • public int indexOf(String str) 返回指定字符str在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回-1。
  • public int indexOf(String str,int fromIndex) 返回从fromIndex位置开始查找指定字符str在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回-1。

语法

public int indexOf(ch)

//或

public int indexOf(ch,int fromIndex)

//或

public int indexOf(String str)

//或

public int indexOf(String str,int fromIndex)

  

参数

ch -- 字符,Unicode 编码。

index -- 开始搜索的索引位置,第一个字符是 0 ,第二个是 1 ,以此类推.

str -- 要搜索的子字符串。

例子

    public static void main(String[] args) {
            String Str = new String("测试字符串:www.google.com");
            String SubStr1 = new String("google");
            String SubStr2 = new String("com");

            System.out.print("查找字符 o 第一次出现的位置 :" );
            System.out.println(Str.indexOf( 'o' ));
            System.out.print("从第14个位置查找字符 o 第一次出现的位置 :" );
            System.out.println(Str.indexOf( 'o', 14 ));
            System.out.print("子字符串 SubStr1 第一次出现的位置:" );
            System.out.println( Str.indexOf( SubStr1 ));
            System.out.print("从第十五个位置开始搜索子字符串 SubStr1 第一次出现的位置 :" );
            System.out.println( Str.indexOf( SubStr1, 15 ));
            System.out.print("子字符串 SubStr2 第一次出现的位置 :" );
            System.out.println(Str.indexOf( SubStr2 ));
    }

以上程序执行结果为:

扫描二维码关注公众号,回复: 8564611 查看本文章
查找字符 o 第一次出现的位置 :11
从第14个位置查找字符 o 第一次出现的位置 :18
子字符串 SubStr1 第一次出现的位置:10
从第十五个位置开始搜索子字符串 SubStr1 第一次出现的位置 :-1
子字符串 SubStr2 第一次出现的位置 :17

  

猜你喜欢

转载自www.cnblogs.com/henrypaul/p/12186314.html
今日推荐