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

 

By | 2012-09-15T14:45:22+00:00 September 15th, 2012|Code Base|2 Comments

About the Author:

2 Comments

  1. Ravinder Kumar March 7, 2015 at 7:19 am - Reply

    its showing an error.. “illegal escape character”

  2. Priya August 26, 2017 at 7:13 am - Reply

    There are some compile time errors after compilation. I tried to resolve it.

Leave A Comment