Java判断一个字符串是否是包含某个字符

Java判断一个字符串是否是包含某个字符

在java中我们经常要判断一个字符串是否被包含在另外一个字符集中,那么如何用代码实现这个功能需求呢?

  • contains方法

该方法返回true,如果此字符串包含,否则返回false。

public class containString
{
    public static void main(String[] args)
    {
        String str1 = "sdfsfsfa2we";
        String str2 = "we";

        System.out.println(str1.contains(str2));
    }
}
  • indexof方法

indexOf的返回值为int

如果找到,则返回找到字符起始字符位置的index索引(从0开始)。

如果未找到,则返回-1

public class containString
{
    public static void main(String[] args)
    {
        String str1 = "sdfsfsfa2we";
        String str2 = "we";

        String str3 = "me";

        System.out.println(str1.indexOf(str2));
        System.out.println(str1.indexOf(str3));
    }
}

猜你喜欢

转载自www.cnblogs.com/zhichun/p/12112538.html
今日推荐