如何在字串中查找片語?

在Java中,如何在字串中查找片語?

此示例顯示了如何使用indexOf()方法在String對象中搜索單詞,該方法返回字串中的單詞的位置索引(如果找到)值。 否則返回-1

package com.zaixian;

public class SearchStringEmp {
    public static void main(String[] args) {
        String strOrig = "Hello, Sukida";
        int intIndex = strOrig.indexOf("Su");

        if (intIndex == -1) {
            System.out.println("Su not found");
        } else {
            System.out.println("Found Su at index : " + intIndex);
        }
    }
}

執行上面示例代碼,得到以下結果 -

Found Su at index : 7

示例2

此示例顯示了如何在String對象中搜索單詞

package com.zaixian;

public class SearchStringEmp2 {
    public static void main(String[] args) {
        String text = "This is my dog, it is name PigPig";
        System.out.print("Is found the word ? " + text.contains("dog"));
    }
}

執行上面示例代碼,得到以下結果 -

Is found the word ? true

上一篇: Java字串 下一篇: Java數組