PROGRAM 19 : ENTER A STRING TO FIND THE LONGEST WORD AND ITS LENGTH.
Example :
PROGRAM :
import java.util.Scanner;
public class wordlengthver2
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to find longest length:");
String str = sc.nextLine();
str = str + " "; // SPACE ADDED TO ENSURE STOPPAGE OF COMPARING AT THE END
int m = 0 , p;
String max = "" , c = ""; // CREATING TEMPORARY VARIABLES
String min = str.substring(0 , str.indexOf(' ')); // EXTRACTS THE FIRST WORD OF STRING
int l = min.length(); // FINDS ITS LENGTH
char ch;
for(int i = 0 ; i<str.length() ; i++){
ch = str.charAt(i);
if(ch!=' ') // CHECKING WHETHER EACH CHARACTER IS A WHITE SPACE OR NOT.
c+=ch; // IF NOT SPACE THAN A WORD IS CREATED
else{
p = c.length(); // LENGTH OF THE EXTRACTED WORD.
if(p>m){ // CHECKS IF THE LENGTH IS GREATER OR NOT
m = p;
max = c;
}
if(p<l){ // CHECKS IF LENGTH IS LESS
min = c;
l = p;
}
p = 0; // RESET TO ZERO FOR ANOTHER WORD
c = "";
}
}
System.out.println();
System.out.println("LONGEST WORD IN STRING: " + max);
System.out.println("LENGTH OF THE LONGEST WORD: " + m);
System.out.println();
System.out.println("SHORTEST WORD IN STRING: " + min);
System.out.println("LENGTH OF THE SHORTEST WORD: " + l);
}
}
No comments:
Post a Comment