首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从任何字符的文本文件中查找最长的单词?

如何从任何字符的文本文件中查找最长的单词?
EN

Stack Overflow用户
提问于 2015-02-26 21:13:40
回答 1查看 7K关注 0票数 0

我的任务是从文本文档中检索最长的单词。我如何调整这一点,以适用于任何语言,如俄语或阿拉伯语。包含数字0-9的单词将被忽略,并在存储前删除单词中的任何标点符号。

例如。53

ex,§“-起诉-Ž,…美国国家统计局(Ž)的调查对象:(C)ŽŽŽŽ“Ž…‰§…”Ž数据

我的代码:

代码语言:javascript
复制
public Collection<String> getLongestWords() {

    String longestWord = "";
    String current;
    Scanner scan = new Scanner(new File("file.txt"));


    while (scan.hasNext()) {
        current = scan.next();
        if (current.length() > longestWord.length()) {
            longestWord = current;

        }
        return longestWord;

    }

}

注意:我以前从未实现过unicode :/

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-26 21:37:44

我相信:(找到并返回文本文件中最长的单词)

代码语言:javascript
复制
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class hello {
     public static void main(String [ ] args) throws FileNotFoundException {
    new hello().getLongestWords();
 }

public String getLongestWords() throws FileNotFoundException {

    String longestWord = "";
    String current;
    Scanner scan = new Scanner(new File("file.txt"));


    while (scan.hasNext()) {
        current = scan.next();
        if (current.length() > longestWord.length()) {
            longestWord = current;
        }

    }
    System.out.println(longestWord);
            return longestWord;
        }

}

带标点符号:

代码语言:javascript
复制
    longestWord.replaceAll("[^a-zA-Z ]", "").split("\\s+");

在你回来之前!

如果你不想用数字来考虑单词:

代码语言:javascript
复制
if ((current.length() > longestWord.length()) && (!current.matches(".*\\d.*"))) {

一切都在一起:

代码语言:javascript
复制
import java.util.Scanner;
import java.io.*;

public class hello {
     public static void main(String [ ] args) throws FileNotFoundException {
    new hello().getLongestWords();
 }

public String getLongestWords() throws FileNotFoundException {

    String longestWord = "";
    String current;
    Scanner scan = new Scanner(new File("file.txt"));


    while (scan.hasNext()) {
        current = scan.next();
        if ((current.length() > longestWord.length()) && (!current.matches(".*\\d.*"))) {
            longestWord = current;
        }

    }
    System.out.println(longestWord);
    longestWord.replaceAll("[^a-zA-Z ]", "").split("\\s+");
            return longestWord;
        }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28752858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档