Skip to content

Commit 719c204

Browse files
committed
Longest Word
1 parent 32545f7 commit 719c204

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/easy/LongestWord.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package easy;
2+
3+
/**
4+
* Have the function LongestWord(sen) take the sen
5+
* parameter being passed and return the largest word in the string.
6+
* If there are two or more words that are the same length,
7+
* return the first word from the string with that length.
8+
* Ignore punctuation and assume sen will not be empty.
9+
*/
10+
public class LongestWord {
11+
12+
/**
13+
* Longest Word function.
14+
*
15+
* @param sen input string
16+
* @return the longest word in a sentence
17+
*/
18+
private static String longestWord(String sen) {
19+
String longest = "";
20+
String cleanWords = sen.replaceAll("[^a-zA-Z0-9 ]", "");
21+
String[] splitWords = cleanWords.split(" ");
22+
for (String splitWord : splitWords) {
23+
if (splitWord.length() > longest.length()) {
24+
longest = splitWord;
25+
}
26+
}
27+
return longest;
28+
}
29+
30+
/**
31+
* Entry point.
32+
*
33+
* @param args command line arguments
34+
*/
35+
public static void main(String[] args) {
36+
var r1 = longestWord("Dwell on the beauty of life. "
37+
+ "Watch the stars, and see yourself running with them.");
38+
System.out.println(r1);
39+
var r2 = longestWord("The happiness of your life depends upon the quality of your thoughts.");
40+
System.out.println(r2);
41+
}
42+
43+
}

0 commit comments

Comments
 (0)