How to print each word in new line in Java - onlyxcodes

Sunday, 30 June 2024

How to print each word in new line in Java

Hello, Developer of Java. I'll demonstrate how to print each word in a new line in Java in this tutorial.


There are several ways in Java to print every word in a string on a separate line. The string must first be separated based on spaces to display each word in the final array. The following provides step-by-step instructions along with various approach examples:


how to print each word in new line in java

1. Using String.split() Method

The String.split() method is used to split a string into an array of substrings based on a specified delimiter, in this case, a space character.


Step-by-Step Guide:


  • Split the string using the split method: This method returns an array of substrings.

  • Iterate through the array: Use a loop to print each array element on a new line.

public class PrintWords 
{
    public static void main(String[] args) 
	{
        // Sample string
        String sentence = "Hello world this is Java";

        // Split the string based on space
        String[] words = sentence.split(" ");

        // Iterate through the array and print each word on a new line
        for (String word : words) {
            System.out.println(word);
        }
    }
}

Output:


Hello
world
this
is
Java

Explanation:


sentence.split(" ") splits the sentence string into an array of words based on spaces.


The for loop iterates through each word in the array and prints it on a new line.


2. Using Scanner Class

The Scanner class can read input and process it token by token. It is an alternative way to split the string and print each word on a new line.


Step-by-Step Guide:


  • Create a Scanner object: Initialize it with the input string.

  • Use Scanner to tokenize the string: Use hasNext() and next() methods to process each word.

Example:


import java.util.Scanner;

public class PrintWords 
{
    public static void main(String[] args) 
	{
        // Sample string
        String sentence = "Hello world this is Java";

        // Create a Scanner object
        Scanner scanner = new Scanner(sentence);

        // Loop to print each word on a new line
        while (scanner.hasNext()) {
            System.out.println(scanner.next());
        }
		
        // Close the scanner
        scanner.close();
    }
}

Output:


Hello
world
this
is
Java

Explanation:


Scanner scanner = new Scanner(sentence) creates a Scanner object with the input string.


while (scanner.hasNext()) checks if there are more tokens (words) to read.


System.out.println(scanner.next()) prints the next token (word) on a new line.


3. Using StringTokenizer Class

The StringTokenizer class provides a way to break a string into tokens. It can be used similarly to Scanner.


Step-by-Step Guide:


  • Create a StringTokenizer object: Initialize it with the input string and delimiter.

  • Use StringTokenizer to iterate through tokens: Use hasMoreTokens() and nextToken() methods to process each word.

Example:


import java.util.StringTokenizer;

public class PrintWords 
{
    public static void main(String[] args) 
	{
        // Sample string
        String sentence = "Hello world this is Java";

        // Create a StringTokenizer object
        StringTokenizer tokenizer = new StringTokenizer(sentence, " ");

        // Loop to print each word on a new line
        while (tokenizer.hasMoreTokens()) {
            System.out.println(tokenizer.nextToken());
        }
    }
}

Output:


Hello
world
this
is
Java

Explanation:


StringTokenizer tokenizer = new StringTokenizer(sentence, " ") creates a StringTokenizer object with the input string and space as the delimiter.


while (tokenizer.hasMoreTokens()) checks if there are more tokens (words) to read.


System.out.println(tokenizer.nextToken()) prints the next token (word) on a new line.


Conclusion:

Printing each word of a string on a new line in Java can be accomplished using various methods such as String.split(), Scanner, and StringTokenizer. Each method has its advantages and can be chosen based on the specific requirements of your application.


String.split(): Simple and straightforward for basic word splitting.


Scanner: Useful when reading input from different sources.


StringTokenizer: A legacy class, still useful for simple tokenization tasks.


Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Context Switching in Java Thread Example

Java Stream Iterate Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad