// Programmer: Fazli Can - November 9, 2015 public class MyClass { public static void main(String args[]) { String testString = "ankara"; String ngramStr = ngram( testString, 0, 4); System.out.println("ngram: " + ngramStr); testString = "istanbul"; ngramStr = ngramCharByChar( testString, 0, 4); System.out.println("ngram: " + ngramStr); testString = "bilkent"; allNgrams (testString); } //============================================================ public static String ngram(String inString, int startNdx, int ngramLen) { String resultStr; int strLen; strLen = inString.length( ); resultStr = ""; if ( startNdx + ngramLen <= strLen) { resultStr = inString.substring (startNdx, startNdx + ngramLen); } return ( resultStr ); } //============================================================ public static String ngramCharByChar(String inString, int startIndex, int ngramLen) { String resultStr; int strLen; strLen = inString.length( ); resultStr = ""; // Create the ngram char by char. for( int i = startIndex; i < startIndex + ngramLen; i++ ) { char nextChar = inString.charAt(i); resultStr = resultStr.concat( String.valueOf(nextChar) ); } return ( resultStr ); } //============================================================ // Generate all possible ngrams of inString public static void allNgrams (String inString) { int inStringLen; inStringLen = inString.length( ); for ( int ngramLength = 1; ngramLength <= inStringLen; ngramLength++ ) { for ( int startIndex = 0; startIndex + ngramLength <= inStringLen; startIndex++ ) { System.out.println ( ngram(inString, startIndex, ngramLength) ); System.out.println ( ngramCharByChar(inString, startIndex, ngramLength) ); } } } // end of allNgrams ( ) } // end of MyClass definition