Longest substring that starts with X and ends with Y | Java program for the above approach ; Function returns length of longest substring starting with X and ending with Y ; Length of string ; Find the length of the string starting with X from the beginning ; Find the length of the string ending with Y from the end ; Longest substring ; Print the length ; Driver code ; Given string str ; Starting and Ending characters ; Function Call
class GFG { public static void longestSubstring ( String str , char X , char Y ) { int N = str . length ( ) ; int start = 0 ; int end = N - 1 ; int xPos = 0 ; int yPos = 0 ; while ( true ) { if ( str . charAt ( start ) == X ) { xPos = start ; break ; } start ++ ; } while ( true ) { if ( str . charAt ( end ) == Y ) { yPos = end ; break ; } end -- ; } int length = ( yPos - xPos ) + 1 ; System . out . print ( length ) ; } public static void main ( String [ ] args ) { String str = " HASFJGHOGAKZZFEGA " ; char X = ' A ' , Y = ' Z ' ; longestSubstring ( str , X , Y ) ; } }