Skip to content

Instantly share code, notes, and snippets.

@bristermitten
Created November 15, 2018 18:38
Show Gist options
  • Save bristermitten/91908c021f1590ee986c73079b3d2e41 to your computer and use it in GitHub Desktop.
Save bristermitten/91908c021f1590ee986c73079b3d2e41 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Scanner;
class CoderbyteLongString {
private static final String REGEX = "[^0-9+a-z+A-Z ]*";
public static String LongestWord(String sen) {
String[] words =
sen.replaceAll(REGEX, "") //filter out any characters that aren't a normal letter or number - remove punctuation
.split(" "); // Split the filtered string into words
return Arrays.stream(words) //Create a Stream (a kind of fancy list) of all of the words
.filter(s -> !s.isEmpty()) //remove any entries in the stream if it's empty. I don't think they should be but just in case
.sorted((s1, s2) -> Integer.compare(s2.length(), s1.length())) //Sort all of the words in order of their length, but backwards, so a Stream of ["I", "love", "dogs"] will become ["dogs", "love", "I"]
.findFirst().get(); //find the first entry in the Stream (in our case "love") and that's the answer
}
//Default stuff for running and parsing input
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(LongestWord(s.nextLine()));
s.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment