Java Substring Comparisons

  • + 0 comments
    public class JavaSubstringComparisons {
        public static void main(String[] args) {
            System.out.println(getSmallestAndLargest("welcometojava", 14));
        }
    
        // Gets the smallest and largest substring with length k from a string s
        public static String getSmallestAndLargest(String s, int k) {
            if (k <= s.length()) {
                String smallestSubstring = s.substring(0, k);
                String largestSubstring = "";
    
                for (int i = 0; i <= s.length() - k; i++) {
                    String substring = s.substring(i, i + k);
                    if (substring.compareTo(smallestSubstring) < 0) {
                        smallestSubstring = substring;
                    }
                    if (substring.compareTo(largestSubstring) > 0) {
                        largestSubstring = substring;
                    }
                }
    
                return smallestSubstring + "\n" + largestSubstring;
            } else {
                return "Substring length cannot be greater than string length";
            }
        }
    }