This java program finds the longest word in a string inputted by the user and prints the number of characters of that word.
Q. Write a program to input a sentence and print the number of characters found in the longest word of the given sentence. For example, if sentence is " India is my country", then the output should be 7.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
class Q32009{ | |
public static void main(String []args){ | |
Scanner s=new Scanner(System.in); | |
String str, word=""; | |
int wl=0,wl1=0; | |
System.out.println("Enter string: "); | |
str=s.nextLine(); | |
str+=" "; | |
int l=str.length(); | |
for(int i=0;i<l;i++){ | |
if(str.charAt(i)==' '){ | |
wl=word.length(); | |
if(wl>wl1){ | |
wl1=wl; | |
wl=0; | |
} | |
word=""; | |
} | |
else{ | |
word+=str.charAt(i); | |
} | |
} | |
System.out.println(wl1); | |
} | |
} |
Comments
Post a Comment