How to find the largest and the smallest word in a string with Java

1 Answer

0 votes
public class FindTheLargestAndSmallestWordInString_Java {
  
    public static void main(String[] args) {
  
        String s = "java c cpp python csharp";
          
        String[] words = s.split(" ");
         
        String maxs = words[0];
        String mins = words[0];
          
        for (String w: words) {
            if (w.length() > maxs.length())
                maxs = w;
            if (w.length() < mins.length())
                mins = w;
        }
        
        System.out.println("The largest word is: " + maxs);
        System.out.println("The smallest word is: " + mins);
    }
}

    
/*
run:
   
The largest word is: python
The smallest word is: c
    
*/

 



answered Mar 20, 2017 by avibootz
edited Oct 10, 2024 by avibootz

Related questions

1 answer 176 views
1 answer 115 views
1 answer 90 views
1 answer 105 views
...