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

Related searches

Currently, I am able to figure out how to display the longest word length. However, is there a way using loops to determine the longest word and also print it out?

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

Here is an solution without split:

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

Output:

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

Program for length of the longest word in a sentence, Given a string, we have to find the longest word in the input string and then calculate the number of characters in this word. Examples: Input : A� Read the sentence using nextLine() method of Scanner class. Now split the sentence into words using split() method and store into a string array. Now set a variable max and initialized to 0. Now check all the words and compare the length of the word and max variables and store the maximum length of the word and print it.


This solution here is slick, and it will actually print out all the words with the longest length, instead of just one.

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

    }
}

I encourage understanding the code though as you stated this is an assignment.

Length of the longest substring without repeating characters , Given a string str, find the length of the longest substring without Break the loop window or not, we store last index of every character in an array lasIndex[]. print the maximum length NRCS also (the above program only prints the Convert Character Array To String In Java � Reverse words in a given� (If you haven't used it before, when using a JList, it can be very helpful to know the length of the longest String in your Java String array.) Other Java String array and for loop examples. For other examples on how to iterate over a Java array, check out this tutorial on How to loop through a Java String array with the Java 5 for loop syntax.


Split the text by space char and find the longest word. Try this code.

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

Input: "It looks good"

Output: Longest word is [Word=looks, WordLength=5, WordIndex=1]

Find the Longest Word in a String (without using the split method , I'm wondering how to solve this without using the str.split method. each character of str (strings are iterable just like arrays) to “build” a word. this with? var currentWord = ""; // unsure about the use of str.length for this loop for build the string. when I try to get it to print out a word it prints out a single letter Counting number of lines, words, characters and paragraphs in a text file using Java; Check if a string contains only alphabets in Java using Lambda expression; Remove elements from a List that satisfy given predicate in Java; Check if a string contains only alphabets in Java using ASCII values; Check if a string contains only alphabets in Java


Use a Pattern and a Matcher and a while loop. Something like,

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

Three Ways to Find the Longest Word in a String in JavaScript, First with a FOR loop, second using the sort() method, and third using the reduce () method. Algorithm Challenge. Return the length of the longest word in the provided sentence. The split() method splits a String object into an array of strings by Without comments: In our case, if we just sort the array Given a string, we have to find the longest word in the input string and then calculate the number of characters in this word. Examples: Input : A computer science portal for geeks Output : Longest word's length = 8 Input : I am an intern at geeksforgeeks Output : Longest word's length = 13


I keep your code, not using array. Here is updated code:

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

Hope it can help.

Java: How to find the longest String in an array of Strings , Other Java String array and for loop examples. For other examples on how to iterate over a Java array, check out this tutorial on How to loop� Previous Next If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions. In this post, we are going to see longest common prefix in array of Strings. So lets say you have string array as below: So Longest common prefix in above String array will be “java” as all above string starts with “java”. Lets take one more


si points to the starting of a new word and we traverse the string using ei. Whenever a space or ‘\0’ character is encountered,we compute the length of the current word using (ei – si) and compare it with the minimum and the maximum length so far.


Convert the string to lowercase to make it case-insensitive. Add an extra space at the end. Now, iterate through the string till space is found and add those character into variable word. Add each word into words array. Array words will hold all the words present in the string. Initialize variable small and large with first word of array.


Java 8 streams are my new golden hammer that I try to use as often as possible with often enormous gains in brevity and readability. Getting multiple return values, such as a maximum value and its associated element, is a bit cumbersome though (and requires an additional "pair" class).