Java is to determine whether a string contains a character

Java is to determine whether a string contains a character

In java we often have to determine whether a string is contained in another character set, then how to use code to achieve this function needs?

  • contains method

This method returns true if this string contains, otherwise false.

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

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

indexOf return value int

If found, it returns the index to find the index character starting character position (starting from 0).

If not found, returns -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));
    }
}

Guess you like

Origin www.cnblogs.com/zhichun/p/12112538.html