首页 > 解决方案 > 检查字符串一是否在java中包含字符串二

问题描述

任务:编写一个接收 2 个字符串参数的方法,并检查第二个字符串是否包含在第一个字符串中。该方法将返回一个布尔值。示例:为“The Witcher”和“Witcher”返回 true。

import java.util.*;

class Dcoder {
    public static void main(String args[]) { 
        System.out.println(method("The Witcher","Witcher"));
    }

    public static boolean method(String str1, String str2) {
        String s1 = "The Witcher";
        boolean s2 = s1.indexOf("Witcher") != -1 ? true : false;
        return s2;
    }
}

我的问题:如何编写代码以便只在 main 方法中指定“The Witcher”和“Witcher”。

标签: javastringindexof

解决方案


用于在您的方法中进行比较的字符串实际上并不是您作为参数传入函数的字符串。此外,Java 中已经有一种方法可以让您轻松地做到这一点,如下所示:

String s1 = "The Witcher";
Boolean result = s1.contains("Witcher");

推荐阅读