繁体   English   中英

如何在不使用数组且仅在 Java 中循环的情况下打印出字符串中最长的单词

[英]How to print out longest word in string WITHOUT using arrays and only loops in Java

目前,我能够弄清楚如何显示最长的字长。 但是,有没有办法使用循环来确定最长的单词并将其打印出来?

    public static void longestWordCalculator(String rawText)
{
    int lengthCounter = 0;
    int finalCounter = 0;
    int textLength = rawText.length();
    for (int i = 0; i < textLength ; i++)
    {
        String indexValue = Character.toString(rawText.charAt(i));
        if(!" ".equals(indexValue))
        {
            lengthCounter++;
        }
        else
        {
            finalCounter = Math.max(finalCounter, lengthCounter);
            lengthCounter = 0;
        }
    }
    System.out.println("Final Value: " + Math.max(finalCounter, lengthCounter));
}

这是一个没有拆分的解决方案:

public class LongestWord {

      public static void longestWordCalculator(String rawText)
      {
          int lastSeparator = -1;
          int maxLength = 0;
          int solPosition = 0;
          int textLength = rawText.length();

          for (int i = 0; i < textLength ; i++)
          {
              //here you may check for other separators
              if (rawText.charAt(i) == ' ') {
                  lastSeparator = i; 
              }
              //assuming no separator is part of a word 
              else {
                  if (i - lastSeparator > maxLength) {
                      maxLength = i - lastSeparator;
                      solPosition = lastSeparator;
                  }
              }
          }
          if (maxLength > 0) {
              String solution = rawText.substring(solPosition+1, solPosition+maxLength+1);
              System.out.println("Longest word is: " + solution);
          }
          else {
              System.out.println("No solution finded!");
          }

      }

      public static void main (String args[]) {
          longestWordCalculator("la casa de mi amigo");
          longestWordCalculator("quiero agua");
          longestWordCalculator("bblablabla");
          longestWordCalculator("");
      }
}

输出:

Longest word is: amigo
Longest word is: quiero
Longest word is: bblablabla
No solution finded!

这个解决方案很巧妙,它实际上会打印出所有长度最长的单词,而不是一个。

public class Main {

    public static void main(String[] args) {

        String string = "one two three four five six seven eight nine";

        String currentWord = "";
        String largestWords = "";
        int longestLength = 0;

        for (int i = 0; i < string.length(); i++) {

            char iteratedLetter = string.charAt(i);
            if (iteratedLetter == ' ') { // previous word just ended.

                if (currentWord.length() > longestLength) {
                    largestWords = "";
                    longestLength = currentWord.length();
                }
                else if (currentWord.length() == longestLength) {
                    largestWords += currentWord + " ";
                }

                currentWord = "";
            }
            else {
                currentWord += iteratedLetter;
            }



        }

        System.out.println("Largest words: " + largestWords);

    }
}

我鼓励理解代码,尽管正如您所说,这是一项任务。

可以使用split()将字符串拆分为字符串数组,然后循环遍历每个元素来检查单词的长度。 在此示例中,我们假设没有特殊字符且单词由空格分隔。

该函数将找到第一个最长的单词,即如果有平局,它将输出长度最长的第一个单词。 在下面的示例中,您可以看到lookinglongest都有相同数量的字符,但它只会输出looking

public static void longestWordCalculator(String rawText)
{
    int textLength = rawText.length();
    String longestWord = "";
    String[] words = rawText.split("\\s");
    for (int i = 0; i < words.length; i++)
    {
        if (words[i].length() > longestWord.length()) {
          longestWord = words[i];
        }
    }
    System.out.println("Longest word: " + longestWord);
    System.out.println("With length of: " + longestWord.length());
}

用法: longestWordCalculator("Hello I am looking for the longest word");

输出

最长的词:看

长度为:7

编辑:

不使用数组:

public static void longestWordCalculator(String rawText)
{
    int nextSpaceIndex = rawText.indexOf(" ") + 1;
    String longestWord = "";
    do {
        String word = rawText.substring(0, nextSpaceIndex);
        rawText = rawText.substring(nextSpaceIndex); // trim string
        if (word.length() > longestWord.length()) {
            longestWord = word;
        }
        int tempNextIndex = rawText.indexOf(" ") + 1;
        nextSpaceIndex = tempNextIndex == 0 ? rawText.length() : tempNextIndex;
    } while (rawText.length() > 0);
    System.out.println("Longest word: " + longestWord);
    System.out.println("With length of: " + longestWord.length());
}

按空格字符拆分文本并找到最长的单词。 试试这个代码。

public class Test {
    public static void longestWordCalculator(String rawText) {
        String[] words = rawText.trim().replaceAll(" +", " ").split(" ");
        int foundIndex = -1;
        int maxLenght = 0;
        String foundWord = "";
        for (int i = 0; i < words.length; i++) {
            if (words[i].length() > maxLenght) {
                maxLenght = words[i].length();
                foundWord = words[i];
                foundIndex = i;
            }
        }
        System.out.println(String.format("Longest word is [Word=%s, WordLength=%s, WordIndex=%s]", foundWord, maxLenght, foundIndex));
    }

    public static void main(String args[]) {
        longestWordCalculator("It looks good");
    }
}

输入:“看起来不错”

输出:最长的单词是 [Word=looks, WordLength=5, WordIndex=1]

使用PatternMatcher以及while循环。 就像是,

public static void longestWordCalculator(String rawText) {
    Pattern p = Pattern.compile("(\\S+)\\b");
    Matcher m = p.matcher(rawText);
    String found = null;
    while (m.find()) {
        String s = m.group(1);
        if (found == null || s.length() > found.length()) {
            found = s;
        }
    }
    if (found == null) {
        System.out.println("No words found");
    } else {
        System.out.printf("The longest word in \"%s\" is %s which is %d characters.%n", 
                rawText, found, found.length());
    }
}

发布的两个答案很好,我会使用它们,但是,如果您想保留当前的实现并避免使用数组等,则可以在使用longestIndex = i - lengthCounter保存新的最长长度时保存当前最长字符串的开始位置longestIndex = i - lengthCounter 最后,打印出rawTextlongestIndexlongestIndex + finalCounter的子字符串。

编辑 - 尝试这样的事情

int lengthCounter = 0;
    int finalCounter = 0;
    int textLength = rawText.length();
    int longestIndex = 0;
    for (int i = 0; i < textLength ; i++)
    {
        String indexValue = Character.toString(rawText.charAt(i));
        if(!" ".equals(indexValue))
        {
            lengthCounter++;
        }
        else
        {
            if (lengthCounter > finalCounter) {
                longestIndex = i - lengthCounter;
                finalCounter = lengthCounter;
            }

            lengthCounter = 0;
        }
    }
    System.out.println("Final Value: " + finalCounter);
    System.out.println("Longest Word: " + rawText.substring(longestIndex, longestIndex + finalCounter));

我保留您的代码,而不是使用数组。 这是更新的代码:

public class Test {
    public static void longestWordCalculator(String rawText) {
        int lengthCounter = 0;
        int finalCounter = 0;
        int textLength = rawText.length();
        StringBuffer processingWord = new StringBuffer();
        String foundWord = null;
        for (int i = 0; i < textLength; i++) {
            String indexValue = Character.toString(rawText.charAt(i));
            if (!" ".equals(indexValue)) {
                processingWord.append(rawText.charAt(i));
                lengthCounter++;

            } else {
                if (finalCounter < lengthCounter) {
                    finalCounter = lengthCounter;
                    foundWord = processingWord.toString();
                    processingWord = new StringBuffer();
                }
                lengthCounter = 0;
            }
        }
        System.out.println("Final Value: " + finalCounter + ", Word: " + foundWord);
    }

    public static void main(String args[]) {
        longestWordCalculator("It looks good");
    }
}

希望它能有所帮助。

暂无
暂无

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

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