Java Program to find the largest and smallest word in a string

Find the smallest and the largest word present in the string

Example:

Input:  Java is programming language
Output: smallest=is, largest=programming

Approach

Java


public class LargeAndSmallWord {
    public static void main(String[] args) {
        String str = "Java is programming language";
        String[] obj = str.split(" ");
        String small = "";
        String large = "";
        for (String string : obj) {
            if (small == "")
                small = string;
            // for largest word check
            if (string.length() > large.length()) {
                large = string;

            }
            // small word check
            if (small.length() > string.length())
                small = string;

        }
        System.out.println("smallest : " + small + ", largest : " + large);
    }
}

Approach

Java

public class LargeAndSmallWord {
    public static void main(String[] args) {
        String str = "Java is programming language";
        String small = "";
        String large = "";
        String strCh = "";
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!Character.isSpaceChar(ch)) {
                strCh = strCh + ch;
                continue;
            }

            if (small == "")
                small = strCh;
            // for largest word check
            if (strCh.length() > large.length()) {
                large = strCh;

            }
            // small word check
            if (small.length() > strCh.length())
                small = strCh;

            // reset
            strCh = "";

        }
        System.out.println("smallest : " + small + ", largest : " + large);
    }
}


No comments:

Post a Comment