Last active 1748454292

Revision fb24894fa315c0997973a5d5ca0153b2cce2aff5

LongestWord.java Raw
1import java.util.*;
2import java.io.*;
3
4class Main {
5
6 public static String LongestWord(String sen) {
7 // Remove punctuation using regex and split by space
8 String[] words = sen.replaceAll("[^a-zA-Z0-9 ]", "").split(" ");
9 String longest = "";
10
11 for (String word : words) {
12 if (word.length() > longest.length()) {
13 longest = word;
14 }
15 }
16 return longest;
17 }
18
19 public static void main(String[] args) {
20 // Test cases
21 System.out.println(LongestWord("fun&!! time")); // Output: time
22 System.out.println(LongestWord("I love dogs")); // Output: love
23 System.out.println(LongestWord("Hello world!123 567")); // Output: Hello
24 }
25}
26