You are on the right track. String.split takes a regular expression (Java details) not literal characters. A dot in a regular expression means "any character", so your split will lots of empty strings, which split
supresses, and you get no output.
You need to escape the dot so that it loses its special meaning and you can match on literal dots. You do that by putting a backslash in front of it. But because backslashes are escape characters themselves in Java Strings, you need to escape the backslash with another backslash: "\\."
.
Then you split each sentence at white space (\s
in regex lingo) and count the words. Add a +
after the \s
to indicate you want one or more spaces, or use *
instead of the +
for zero to many (any number).
Here is a complete example:
public class LongestSentenceOfMany {
public static void main(String[] args) {
String input = "Hello, my name is Pedro. I want to go to Paris. I'm going to buy the ticket";
// String[] sentences = input.split("\\.");
String[] sentences = input.split("\\s*\\.\\s*");
String longestSentence = null;
int longestCount = -1;
for (String sentence : sentences) {
String[] words = sentence.split("\\s+");
System.out.println("\"" + sentence + "\" has " + words.length + " words.");
if (longestSentence == null || words.length < longestCount) {
longestSentence = sentence;
}
}
if (longestSentence != null) {
System.out.println("\"" + longestSentence + "\" is the longest sentence");
}
}
}