how to check if a string contains a substring java code example
Example 1: java if string contains character
if (string.contains(character)
Example 2: find a substring in a string java
package hello;
public class SubStringProblem {
public static void main(String[] args) {
System.out
.println("Checking if one String contains another String using indexOf() in Java");
String input = "Java is the best programming language";
boolean isPresent = input.indexOf("Java") != -1 ? true : false;
if (isPresent) {
System.out.println("input string: " + input);
System.out.println("search string: " + "Java");
System.out.println("does String contains substring? " + "YES");
}
System.out.println("Doing search with different case");
isPresent = input.indexOf("java") != -1 ? true : false;
System.out.println("isPresent: " + isPresent);
System.out
.println("Checking if one String contains another String using contains() in Java");
input = "C++ is predecessor of Java";
boolean isFound = input.contains("Java");
if (isFound) {
System.out.println("input string: " + input);
System.out.println("search string: " + "Java");
System.out.println("does substring is found inside String? " + "YES");
}
System.out.println("Searching with different case");
isFound = input.contains("java");
System.out.println("isFound: " + isFound);
}
}
Output
Checking if one String contains another String using indexOf() in Java
input string: Java is the best programming language
search string: Java
does String contain substring? YES
Doing search with different case
isPresent: false
Checking if one String contains another String using contains() in Java
input string: C++ is the predecessor of Java
search string: Java
does substring is found inside String? YES
Searching for different case
isFound: false
Example 3: java string contains char
public static boolean contains_char (String main, char secondary)
{
boolean contains_result = false;
for (int i = 0 ; i < input.length () ; i++)
{
if (input.charAt (i) == secondary)
{
contains_result = true;
break;
}
}
return contains_result;
}
public static boolean contains_dualchar (String main, String secondary)
{
boolean contains_result = false;
for (int i = 0 ; i < input.length () ; i++)
{
if (input.charAt (i) == secondary.charAt (0))
{
if (input.charAt (i + 1) == secondary.charAt (1))
{
contains_result = true;
break;
}
}
}
return contains_result;
}
Example 4: string check if substring exists java
String str1 = "Java";
String str2 = "va";
if(str1.contains(str2)){
System.out.println("I am true");
}