Understanding Java Scanner's useDelimiter and Its Practical Uses with Examples

06 May 2023 Balmiki Mandal 0 Core Java

Java Scanner useDelimiter with Examples

The useDelimiter() is a method in Java Scanner class which is used to set the delimiting pattern of a Scanner object. By default, a Scanner object uses a space character as its delimiter.

This method returns the current Scanner object which then allows us to chain methods together. It accepts a String parameter which contains the delimiting pattern. The pattern can be any regular expression and it will be used to match the tokens while parsing the input string.

Let's look at some examples of using the useDelimiter() method.

Example 1: Setting a New Delimiter

The following example scans the given String, splits tokens by comma.


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		String str = "John,Doe,21";

		// Create a Scanner object
		Scanner sc = new Scanner(str);

		// Use comma as the delimiter
		sc.useDelimiter(",");

		// Print the tokens
		System.out.println(sc.next());
		System.out.println(sc.next());
		System.out.println(sc.next());
	}
}

Output:

John
Doe
21

Example 2: Using Multiple Delimiters

The following example scans the given String, splits tokens by three different delimiters: comma, hyphen, and white-space.


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		String str = "John-Doe,21,Male";

		// Create a Scanner object
		Scanner sc = new Scanner(str);

		// Use multiple delimiters: comma, hyphen and whitespace
		sc.useDelimiter("[,-\\s]");

		// Print the tokens
		System.out.println(sc.next());
		System.out.println(sc.next());
		System.out.println(sc.next());
	}
}

Output:

John
Doe
21

Example 3: Using Regular Expression to Match Text

The following example scans the given String, splits tokens by matching a regular expression which looks for integers.


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		String str = "John-Doe,21,Male";

		// Create a Scanner object
		Scanner sc = new Scanner(str);

		// Use regular expression to find integers
		sc.useDelimiter("\\d+");

		// Print the tokens
		System.out.println(sc.next());
		System.out.println(sc.next());
		System.out.println(sc.next());
	}
}

Output:

John-Doe,
,Male

Conclusion

In this tutorial, we learned about the useDelimiter() method of the Scanner class in Java. We also saw how it can be used to set the delimiting pattern of a Scanner object.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.