Skip to content

Commit 183acf4

Browse files
committed
[Manan] ADD:Finding the longest word in a string
1 parent 054195b commit 183acf4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

LongestWord.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.Scanner;
2+
3+
class LongestWord {
4+
// Main method
5+
public static void main(String[] args) {
6+
Scanner input = new Scanner(System.in);
7+
8+
System.out.print("Enter a string: ");
9+
String str = input.nextLine();
10+
11+
// Method to find the longest word in a string
12+
String result = longestWord(str);
13+
14+
System.out.println("Longest word in the string: " + result);
15+
}
16+
17+
// Method to find the longest word in a string
18+
public static String longestWord(String str) {
19+
String[] words = str.split(" ");
20+
String longestWord = "";
21+
for (String word : words) {
22+
if (word.length() > longestWord.length()) {
23+
longestWord = word;
24+
}
25+
}
26+
return longestWord;
27+
}
28+
}

0 commit comments

Comments
 (0)