LongestWord.java
· 747 B · Java
Raw
import java.util.*;
import java.io.*;
class Main {
public static String LongestWord(String sen) {
// Remove punctuation using regex and split by space
String[] words = sen.replaceAll("[^a-zA-Z0-9 ]", "").split(" ");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
return longest;
}
public static void main(String[] args) {
// Test cases
System.out.println(LongestWord("fun&!! time")); // Output: time
System.out.println(LongestWord("I love dogs")); // Output: love
System.out.println(LongestWord("Hello world!123 567")); // Output: Hello
}
}
1 | import java.util.*; |
2 | import java.io.*; |
3 | |
4 | class 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 |