Check if String Contains another String
To check if a string contains another string the method indexOf() is used. It returns the index in the haystack string where the needle string begins. If the needle string is not present in the haystack string, the value -1 is returned. In the code example below we check two needle strings against a haystack string, one exists and one does not. |
/** * Main.java * * @author www.javadb.com */ public class Main { /** * Checks if string contains another string. */ public void checkStringContains() { String haystack = "Programming in Java"; String needle1 = "Java"; String needle2 = "Pascal"; int index1 = haystack.indexOf(needle1); int index2 = haystack.indexOf(needle2); if (index1 != -1) System.out.println("The string contains the substring " + needle1); else System.out.println("The string does not contain the substring " + needle1); if (index2 != -1) System.out.println("The string contains the substring " + needle2); else System.out.println("The string does not contain the substring " + needle2); } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().checkStringContains(); } } |
If the code example above is executed, the output will be: |
The string contains the substring Java The string does not contain the substring Pascal |
Search for code examples on this site
