我能够在文本文件中找到最长的单词,现在我正在努力寻找最长的单词。算法是否类似于搜索最长的单词? 这是我的代码,找到最长的单词:
public static int getLongestWord() throws FileNotFoundException {
String longestWord = "";
String current;
Scanner scan = new Scanner(new File("t1.txt"));
while (scan.hasNext()) {
current = scan.next();
if (current.length() > longestWord.length()) {
longestWord = current;
}
}
scan.close();
return longestWord.length();
}
UPDATE! 谢谢您的帮助。我能够得到最长的单词,现在我正在计算最长句子中的单词数量。不知何故,柜台有点偏。 这就是我所拥有的:
public static String getLongestSentence() throws FileNotFoundException {
int numWords = 0;
String longestSentence = "";
String currentSentence = "";
Scanner scan = new Scanner(new File("t1.txt"));
while (scan.hasNext()) {
currentSentence = getNextSentence(scan);
if (currentSentence.length() > longestSentence.length()) {
longestSentence = currentSentence;
}
}
scan.close();
String[] wordList = longestSentence.split("\\s+");
numWords += wordList.length;
System.out.println(longestSentence);
System.out.println("Number of words in this sentence: " + numWords);
return longestSentence;
}
private static String getNextSentence(Scanner scan) {
String sentence = "";
while (scan.hasNext()) {
sentence += " " + scan.next();
if (sentence.contains("."))
break;
}
return sentence;
}
我的文本文件中最长的句子包含30个单词,但我的计数器关闭了1,表示它有31个单词。知道为什么吗?感谢。
答案 0 :(得分:1)
File file = new File("sentences.txt");
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
String fullContent = "";
while(line != null && line.length() > 0) {
fullContent += line;
line = br.readLine();
}
private static String[] getSentences(String file) {
return file.split("\\.");
}
public static int getMaxWordLength(String sentence, int maxWordLength) {
for(String word : sentence.split(" ")) {
String wordLength = word.trim().length();
if(wordLength > maxWordLength) {
maxWordLength = wordLength;
}
}
return maxWordLength;
}
int length = 0;
String largestSentence = null;
for(String sentence : getSentences(fullContent)) {
int maxWordLength = 0;
maxWordLength = getMaxWordLength(sentence, maxWordLength);
if(maxWordLength > length) {
largestSentence = sentence;
length = maxWordLength;
}
}
System.out.println(largestSentence);
答案 1 :(得分:0)
你需要考虑两件事:
您认为任何句子以'结尾。
那么你可能会选择这样的东西public static String getLongestSentence() throws FileNotFoundException {
String longestSentence = "";
String currentSentence = "";
Scanner scan = new Scanner(new File("t1.txt"));
while (scan.hasNext()) {
currentSentence = getNextSentence(scan);
if (currentSentence.length() > longestSentence.length()) {
longestSentence = currentSentence;
}
}
scan.close();
return longestSentence;
}
private static String getNextSentence(Scanner scan) {
String sentence = "";
while(scan.hasNext()){
sentence += scan.next();
if(sentence.contains(".")) break;
}
return sentence;
}
OR 如果你想考虑更多真实案例,比如elippsis,ASCII怪异代码,其他语言,那么......你将需要看看像{{3这样的文本分析器因为从头开始做会给你带来无限的麻烦。