如何在字符串中查找词组?

在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数组