Split a String Using scannner Class in Java

In this article we will learn to split the string using Scanner Class.

To know how to split string using split method in String visit Here. Or you can visit this article to know how to so the same using StringTokenizer.

package com.jbt;

import java.util.Scanner;

/*
 * In this code Scanner class will be used to split a String
 */
public class SplitStringUsingScannerClass {

	public static void main(String args[]) {
		String str = "Java Beginners Tutorial version 1";

		/*
		 * Scanner is a Class from java.util package. Constructs a new Scanner
		 * that produces values scanned from the specified string.
		 * useDelimiter() method is used to set this scanner's delimiting
		 * pattern to a pattern constructed from the specified String.
		 */
		Scanner scanner = new Scanner(str).useDelimiter("\s");

		/*
		 * We can directly use the next method to finds and returns the next
		 * complete token from this scanner. Retrun type would be String
		 */

		while (scanner.hasNext())
			System.out.println(scanner.next());

		/*
		 * Scanner can also scan primitives along with Strings. And scanners
		 * have different method for different primitives type.
		 * Scans the next token of the input as a
		 * 1- nextBigDecimal : BigDecimal
		 * 2- nextBigInteger(): BigInteger
		 * 3- nextBoolean() : Boolean
		 * 4- nextByte() : Byte
		 * 5- nextDouble() : Double
		 * 6- nextFloat() : Float
		 * 7- nextInt() : Int
		 * .....
		 */

		System.out
				.println("nSplitting the String and using Primitive Specific methodsn");
		String strAgain = "Java version 1 and 2 true";
		Scanner scannerAgain = new Scanner(strAgain).useDelimiter("\s");
		System.out.println(scannerAgain.next());
		System.out.println(scannerAgain.next());
		System.out.println(scannerAgain.nextInt());
		System.out.println(scannerAgain.next());
		System.out.println(scannerAgain.nextInt());
		System.out.println(scannerAgain.nextBoolean());
		scanner.close();
	}
}

Output of the above code would be

Java
Beginners
Tutorial
version
1

Splitting the String and using Primitive Specific methods

Java
version
1
and
2
true

 

6 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.