Introduction
In this lab, we will learn how to find a word or substring in a Java String. We will use the indexOf()
and contains()
methods of the String class to locate the substring in the given String.
In this lab, we will learn how to find a word or substring in a Java String. We will use the indexOf()
and contains()
methods of the String class to locate the substring in the given String.
Let's create a Java file where we will write our Java code. Open the terminal and create a Java file using the following command:
touch ~/project/FindWordInString.java
Here, FindWordInString
is the name of our Java file.
indexOf()
methodIn this step, we will use the indexOf()
method to find the index of the specified substring in the given String. If the substring is present in the String, it returns its starting index, otherwise, it returns -1.
public class FindWordInString {
public static void main(String[] args) {
String str = "This sentence contains the word find me";
System.out.println(str);
String find = "find me";
int index = str.indexOf(find);
if (index >= 0) {
System.out.println("Word found at index: " + index);
} else {
System.out.println("Word not found");
}
}
}
Run the code using the following command:
javac FindWordInString.java && java FindWordInString
You should see the output as:
This sentence contains the word find me
Word found at index: 31
contains()
methodIn this step, we will use the contains()
method to check if the given String contains the specified substring or not. If it is present, it returns true, otherwise, it returns false.
public class FindWordInString {
public static void main(String[] args) {
String str = "This sentence contains the word find me";
System.out.println(str);
String find = "find me";
boolean found = str.contains(find);
if (found) {
System.out.println("Word found");
} else {
System.out.println("Word not found");
}
}
}
Run the code using the following command:
javac FindWordInString.java && java FindWordInString
You should see the output as:
This sentence contains the word find me
Word found
In this lab, we learned how to find a word or substring in a Java String using indexOf()
and contains()
methods. We created a Java file and wrote the Java code to find the substring in the given String. We also learned how to run the Java code using the command line in Ubuntu.