Java:找出字符串中最短的单词并打印出来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12326899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:27:05  来源:igfitidea点击:

Java: Finding the shortest word in a string and printing it out

javaarraysstringloops

提问by Batteries

I'm a novice with Java. I took a class in C, so I'm trying to get myself out of that mode of thinking. The program I'm writing has a section in which the user enters an integer, n, and then nnumber of words afterwards. This section then searches through those words and finds the shortest one, then returns it to the user. For instance, an input might be:

我是 Java 的新手。我上了一门 C 课,所以我试图让自己摆脱那种思维模式。我正在编写的程序有一个部分,用户在其中输入一个整数n,然后输入n个单词。此部分然后搜索这些词并找到最短的词,然后将其返回给用户。例如,输入可能是:

INPUT:4 JAVA PROGRAMMING IS FUN

OUTPUT:IS

输入:4 JAVA 编程很有趣

输出:

The code I have currently seems to return the wrong word. In this instance, it returns "PROGRAMMING", when it should return "IS". I thought maybe you all could point me in the right direction.

我目前拥有的代码似乎返回了错误的单词。在这种情况下,它返回“PROGRAMMING”,而它应该返回“IS”。我想也许你们都可以指出我正确的方向。

int numwords = scan.nextInt();
    String sentence = scan.nextLine();
    String shortestword = new String();
    String[] words = sentence.split(" ");
    for (int i = 0; i < numwords; i++){
        if (shortestword.length() < words[i].length()){
            shortestword = words[i];

        }
    }
    System.out.printf(shortestword);

To give you an idea of what I was trying to do, I was attempting to enter the words into a string, "sentence," then break that string up into individual words in an array, "words[]," then run a for loop to compare the strings to each other by comparing the lengths to the entries in the array. Thank you for your assistance!

为了让您了解我正在尝试做什么,我试图将单词输入字符串“sentence”,然后将该字符串分解为数组中的单个单词“words[]”,然后运行 ​​for循环通过将长度与数组中的条目进行比较来相互比较字符串。谢谢您的帮助!

回答by Jo?o Silva

You're almost there, but your comparison to detect the shortest word is reversed. It should be:

你快到了,但是你检测最短单词的比较被颠倒了。它应该是:

if (words[i].length() < shortestword.length()) {

That is, if your current word's length is less than the length of your previous shortest word, overwrite it.

也就是说,如果您当前单词的长度小于您之前最短单词的长度,则覆盖它。

Also, instead of starting with an empty String, start with the firstword, i.e., words[0]. Otherwise, the empty string will always be shorter than any string in your array:

此外,不要以空String开头,而是以第一个单词开头,即words[0]。否则,空字符串将始终比数组中的任何字符串短:

String[] words = sentence.split(" ");
String shortestword = words[0];
for (int i = 1; i < numwords; i++) { // start with 1, because you already have words[0]

回答by fatrock92

Your if statement is wrong. This should work.

你的 if 语句是错误的。这应该有效。

int numwords = scan.nextInt();
    String sentence = scan.nextLine();
    String shortestword = new String();
    String[] words = sentence.split(" ");
    for (int i = 0; i < numwords; i++){
        if (shortestword.length() > words[i].length()){
            shortestword = words[i];

        }
    }
    System.out.printf(shortestword);

回答by Matthias Braun

Here's a version that makes use of Java 8's Stream API:

这是一个使用 Java 8 的Stream API 的版本

String sentence = "PROGRAMMING IS FUN";
List<String> words = Arrays.asList(sentence.split(" "));

String shortestWord = words.stream().min(
                                     Comparator.comparing(
                                     word -> word.length()))
                                    .get();

System.out.println(shortestWord);

You can also sort more complex objects by any of their attribute: If you have a couple of Persons and you wanted to sort them by their lastName, shortest first, the code becomes:

您还可以按任何属性对更复杂的对象进行排序:如果您有几个Persons 并且您想按它们的s 对它们进行排序lastName,最短的在先,代码变为:

Person personWithShortestName = persons.stream().min(
                                                 Comparator.comparing(
                                                 person -> person.lastName.length()))
                                                .get();

回答by Sufiyan Ghori

Java 8has made it simpler. Convert your Stringarray to a list and use sorted()to compare and sort your list in ascending order. Finally, use findFirst()to get the first value of your list (which is shortest after sorting).

Java 8让它变得更简单。将您的String数组转换为列表并用于sorted()按升序比较和排序您的列表。最后,用于findFirst()获取列表的第一个值(排序后最短)。

have a look,

看一看,

String[] words = new String[]{"Hello", "name", "is", "Bob"};
String shortest = Arrays.asList(words).stream()
      .sorted((e2, e1) -> e1.length() > e2.length() ? -1 : 1)
      .findFirst().get();

System.out.println(shortest);