class Find { // this class solves problem P5.24 in the textbook // in two ways: one with recursion, one without. // this method looks for the string 't' inside // the supposedly larger string 's' public static int find( String s, String t ) { int si=0, ti=0; while( si <= s.length() - t.length() ) { // look inside String s, at position si String partOfS = s.substring( si, si+t.length() ); // start ^^, ^^^^^^^^^^^^^ pastEnd if( partOfS.equals( t ) ) // compare strings return si; // found at position si si++; } return -1; // not found } // this method looks for the string 't' inside // the supposedly larger string 's' public static int findRecursive( String s, String t ) { if( s.length() < t.length() ) return -1; // base case, s is too small; not found // look at first part of S String firstPartOfS = s.substring( 0, t.length() ); // check if String s starts off with String t if( firstPartOfS.equals( t ) ) // compare strings return 0; // found at position 0 of s else { // Recurse by removing first character from s, // and looking for t in the remainder of s. // If we found it, we must find the position in // s by counting as the recursion unrolls. int found = findRecursive( s.substring(1), t ); if( found < 0 ) return -1; // didn't find it, keep -1 else return 1+found; // count the positions } } public static void main( String[] args ) { // use 4 simple test cases. more should be used. // first case: returns 1, the first match (multiple matches) // second case: returns 0, matching at beginning of s // third case: returns 9, matching at end of s // fourth case: returns -1, no match System.out.println( find( "Mississippi", "is" ) ); System.out.println( find( "Mississippi", "Miss" ) ); System.out.println( find( "Mississippi", "pi" ) ); System.out.println( find( "Mississippi", "hip" ) ); System.out.println( findRecursive( "Mississippi", "is" ) ); System.out.println( findRecursive( "Mississippi", "Miss" ) ); System.out.println( findRecursive( "Mississippi", "pi" ) ); System.out.println( findRecursive( "Mississippi", "hip" ) ); } }