Welcome To The World Of Java

This site will teach you the basics of Java. It is not necessary to have any prior programming experience.

Java program to finding Shortest and Longest Words in a String.

Somdeb Burman | 12:19:00 PM | 1 comments

import java.io.BufferedReader;
class FindMinMaxString {
 public static void main(String args[]) {
  findMethod("My name is Umesh Kushwaha");
 }
 static public void findMethod(String s) {
  String str = s + " ";
  char ch = ' ';
  int len = str.length(), l = 0;
  int min = len, max = 0;
  String shortest_word = "", longest_word = "", word = "";
  for (int i = 0; i < len; i++) {
   ch = str.charAt(i);
   if (ch != ' ') {
    word += ch;
   }                                     //if ends
   else {
    l = word.length();
    if (l < min) {
     min = l;
     shortest_word = word;
    }                                     //if ends
    if (l > max) {
     max = l;
     longest_word = word;
    }
    word = "";
   }
  }
  System.out.println("Shortest word = " + shortest_word + " with length " + min);
  System.out.println("Longest word = " + longest_word + " with length " + max);
 }
}

Output:
Shortest word = My with length 2
Longest word = Kushwaha with length 8

Java Resources are available for Download from below

Category: , , , ,

1 comment:

  1. In your example "is" also smallest word but it is printed.Somewhere logic is missing, Pls check

    ReplyDelete