简体   繁体   English

输出文本文件中最长的单词

[英]Output the longest word in a text file

I have created a text file writes every word written in the editText box of the android app. 我创建了一个文本文件,用于编写android app的editText框中写的每个单词。 I also tried to read the contents of the file using bufferedreader . 我还尝试使用bufferedreader读取文件的内容。 The problem is, I want to get an output only the longest word in the list created but I can't seem to compare all the strings inputted. 问题是,我想得到一个输出只是创建列表中最长的单词,但我似乎无法比较输入的所有字符串。 My googling only provided info about comparing the length of two strings. 我的谷歌搜索只提供了有关比较两个字符串长度的信息。 How can I compare the length of each line in the text file? 如何比较文本文件中每行的长度? Can anyone please guide me on what to do next? 任何人都可以指导我下一步做什么?

my code looks like this: 我的代码看起来像这样:

 try
   {
        File myFile = new File("/sdcard/logger.file");
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(
                new InputStreamReader(fIn));
        String aDataRow = "";
        String aBuffer = "";
        while ((aDataRow = myReader.readLine()) != null)
        {
            aBuffer += aDataRow + "\n";
        }
        show.setText(aBuffer);
        myReader.close();
        Toast.makeText(getBaseContext(),
                "Done reading SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
        }
   catch (Exception e) 
   {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
   }
}

i don't know what your textfile looks like, but if you only have a single word each line, you can use your comparation of two strings. 我不知道你的文本文件是什么样的,但是如果每行只有一个单词,你可以使用两个字符串的比较。 in fact that you already "touch" each word/line while reading it out from the file, why you don't just compare them right there? 事实上,你已经从文件中读出了每个单词/行的“触摸”,为什么你不只是在那里比较它们? i modified your code, so that it should do what you want it to do. 我修改了你的代码,以便它可以做你想做的事情。

try
{
    File myFile = new File("/sdcard/logger.file");
    FileInputStream fIn = new FileInputStream(myFile);
    BufferedReader myReader = new BufferedReader(
            new InputStreamReader(fIn));
    String longestString ="";
    String aDataRow = "";
    String aBuffer = "";
    while ((aDataRow = myReader.readLine()) != null)
    {
        if(longestString.length()<=aDataRow.length()){
            longestString = aDataRow;
        }
        aBuffer += aDataRow + "\n";
    }
    //So here you defenitly got your longestWord in "longestString"
    show.setText(aBuffer);
    myReader.close();
    Toast.makeText(getBaseContext(),
            "Done reading SD 'mysdfile.txt'",
            Toast.LENGTH_SHORT).show();
    }
catch (Exception e) 
{
    Toast.makeText(getBaseContext(), e.getMessage(),
            Toast.LENGTH_SHORT).show();
}

You can use java.util.Scanner, 你可以使用java.util.Scanner,

    try
   {
        File myFile = new File("/sdcard/logger.file");
        Scanner scanner = new Scanner(myFile);
        String bigWord = "";
        while (scanner.hasNextLine()) {
            Scanner wordScanner = new Scanner(scanner.nextLine());
            while (wordScanner.hasNext()) {
                String str = wordScanner.next();
                if(str.length() > bigWord.lenght())
                    bigWord = str;
            }
        }
        show.setText(bigWord);
        Toast.makeText(getBaseContext(),
                "Done reading SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
   }
   catch (Exception e) 
   {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
   }
}

An easy to understand method to solve this problem is to break it into two steps. 解决此问题的一种易于理解的方法是将其分为两个步骤。

The first step is to read all of your separate words into a big array or list. 第一步是将所有单独的单词读入一个大数组或列表。 The second step is to go through the array or list, and find the longest word. 第二步是遍历数组或列表,找到最长的单词。 I'm not sure if you want to get the longest line or the longest word. 我不确定你是想要获得最长的一行还是最长的一个词。 Maybe they're the same. 也许他们是一样的。

Anyway, for your problem specifically, you need to have: 无论如何,特别针对您的问题,您需要:

List lines = new ArrayList<>(); List lines = new ArrayList <>();

Then you need to replace aBuffer += aDataRow + "\\n"; 然后你需要替换aBuffer + = aDataRow +“\\ n”; with this: lines.add(aDataRow); 用这个:lines.add(aDataRow);

Then when you have finished reading the file, you simply have to have some code like this: 然后当你读完文件后,你只需要有这样的代码:

int biggest = 0;
String big_word = "";
for (String row : lines) {
    if (row.length() > biggest) {
        biggest = row.length();
        big_word = row;
    }
}

Toast.makeText(getBaseContext(), "Biggest word is " + big_word, Toast.LENGTH_SHORT).show();

People will recognise that you can combine the creation of the list and the reading of the file, but this method is easier to understand. 人们会认识到您可以组合列表的创建和文件的读取,但这种方法更容易理解。

Guava solution: 番石榴解决方案:

    String longestWord = Files.readLines(new File("/sdcard/logger.file"), Charsets.UTF_8, 
        new LineProcessor<String>() {

            TreeSet<String> set = new TreeSet(new Comparator<String>() {
                @Override public int compare(String o1, String o2) {
                    return o1.length() - o2.length();
                }
            });

         @Override public boolean processLine(String line) {
             set.addAll(Sets.newHashSet(Splitter.on(" ").split(line)));
             return true;
         }

         @Override public String getResult() {
            return set.last();
         }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM