java中判断一个字符串是否含有子字符串(子

如题所述

完整代码如下(关键代码加注释):

public class Test {

    // 参数是需要判断的子字符串
    public void judge(String subString) {

        String string = "judge is subString";

        // 返回指定子字符串在此字符串中第一次出现处的索引。如果它不作为一个子字符串出现,则返回 -1。
        if (string.indexOf(subString) == -1) {
            System.out.println("此字符串中不含" + subString + "这个子字符串");
        } else {
            System.out.println("此字符串中含有" + subString + "这个子字符串");
        }
    }

    // 主方法
    public static void main(String[] args) {

        Test test = new Test();
        test.judge("sub");
    }

}

允许结果:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-01-20

String a = "This is a test string";
if (a.indexOf("is")>=0) {
  System.out.println("found it ");
} else {
  System.out.println("not found");
}

相似回答