Java中字符串indexof() 的使用方法

Java中字符串中子串的查找共有四种方法(indexof())

indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

Java中字符串中子串的查找共有四种方法,如下:
1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 
2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 
4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

example:统计指定字符串在当前字符串中出现的次数

public static void main(String[] args) {

        String str = "ghabcdefghffghfd";

        int count = 0;
                //方式一,使用正则表达式 
        // Pattern pattern = Pattern.compile("gh");
        // Matcher matcher = pattern.matcher(str);
        // while (matcher.find()) {
        // count++;
        // }
                //方式二,使用public int indexOf(String str)返回指定子字
                //符串在此字符串中第一次出现处的索引。
              //  参数:
              //  str - 任意字符串。 
              //  返回:
              //  如果字符串参数作为一个子字符串在此对象中出现,则返回第
             //   一个这种子字符串的第一个字符的索引;如果它不作为一个子
              //  字符串出现,则返回 -1。

        int index = 0;
        while ((index = str.indexOf("gh", index)) != -1) {

            index += "gh".length();
            count++;
        }
        System.out.println(count);

    }

 

posted @ 2018-02-04 17:43  ___struggle  阅读(2155)  评论(0编辑  收藏  举报