Java-Change Delimiters

Change Delimiters

Scanner defines where a token starts and ends based on a set of delimiters. The default delimiters are the whitespace characters. However, it is possible to change the delimiters by calling the useDelimiter(String pattern) method, pattern is a regular expression that specifies the delimiter set. For example, in the following program, the String str are separated by caret, ampersand and asterisk. The use of the delimiter pattern “[*&^]” tells ¬†Scanner to match a caret, ampersand and asterisk as delimiters. You can obtain the current delimiter pattern by calling delimiter( ) method.

Program

new


Program Source

import java.util.Scanner;

public class Javaapp {
  
    public static void main(String[] args) {
        
        String str = "10A*20B&30C^40D*50E&60F";
        
        Scanner instr = new Scanner(str);
        instr.useDelimiter("[*&^]");
        
        while(instr.hasNext())
        {
            System.out.println("Token : "+instr.next());
        }
        instr.close();
        System.out.println(instr.delimiter());
    }
}

Leave a Comment