Extract a Substring Between Two Characters in a String in Java
Last Updated :
09 Feb, 2024
In Java, the extraction of the substring between the two characters in a string can be implemented with the substring method, and string is a pre-defined method in the class of the String. A String is a pre-defined class of the java.lang package.
substring(startIndex, endIndex): This is a pre-defined method of the String class, and it takes the two parameters are starting index and ending index of the string can extract the substring.
Step-by-step Implementation
- Create the main method in the Java program.
- Define the one static with a string value.
- Take the startChar and endChar as characters after that find the index of the characters with the indexOf() method.
- Give the startIndex and endIndex, the parameters of the substring method then it finds the substring of the specific between of two characters.
- Print the substring.
Program to Extract a Specific Substring between Two Characters in a String in Java
Java
import java.lang.String;
public class GFGSubStringExample {
public static void main(String[] args) {
String inputString = "Welcome to the Geeks for Geeks Tutorial" ;
char startChar = 'h' ;
char endChar = 't' ;
int startIndex = inputString.indexOf(startChar);
int endIndex = inputString.indexOf(endChar, startIndex + 1 );
if (startIndex != - 1 && endIndex != - 1 ) {
String result = inputString.substring(startIndex + 1 , endIndex);
System.out.println( "Substring between '" + startChar + "' and '" + endChar + "': " + result);
} else {
System.out.println( "Not found" );
}
}
}
|
Output
Substring between 'h' and 't': e Geeks for Geeks Tu
Explanation of the Program:
- The above the program is the example of the extract the specific substring between two characters in a string.
- It is easy to implement in the Java program to obtain the starting and ending characters.
- And it has the index values using the substring method to extract the substring between the characters.
Share your thoughts in the comments
Please Login to comment...