有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在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));
}

共 (6) 个答案

  1. # 1 楼答案

    我保留你的代码,不使用数组。以下是更新代码:

    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");
        }
    }
    

    希望能有所帮助

  2. # 2 楼答案

    使用^{}^{}以及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());
        }
    }
    
  3. # 3 楼答案

    这个解决方案很灵活,它可以打印出所有最长的单词,而不是一个

    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);
    
        }
    }
    

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

  4. # 4 楼答案

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

    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]

  5. # 5 楼答案

    发布的两个答案很好,我会使用它们,但是如果您想保留当前的实现并避免数组等,可以在使用^{保存新的最长长度时保存当前最长字符串的开头位置。最后,将rawText中的子字符串从longestIndex打印到longestIndex + 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));
    
  6. # 6 楼答案

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

    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!