1. 程式人生 > >Java中字符串indexof() 的使用方法

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

子字符串 表達 .net print indexof bcd sys out 則表達式

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); }

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