To find a substring between two strings in Java, you can use the indexOf()
method to find the starting and ending indices of the two strings, and then use the substring()
method to extract the desired substring.
Here's an example of how to do it:
public class Main { public static void main(String[] args) { String input = "The quick brown fox jumps over the lazy dog."; String start = "quick"; String end = "lazy"; // Find the indices of the start and end strings int startIndex = input.indexOf(start); int endIndex = input.indexOf(end); // Check if the start and end strings were found if (startIndex >= 0 && endIndex >= 0) { // Extract the substring between the start and end strings String substring = input.substring(startIndex + start.length(), endIndex); System.out.println(substring); // prints " brown fox jumps over the " } else { System.out.println("Start or end string not found."); } } }
This code creates a string and then uses the indexOf()
method to find the indices of the start
and end
strings. The substring()
method is then used to extract the substring between the two strings.