Sean Hwang Sean Hwang - 3 years ago 84
Java Question

Java String Split with multiple delimiter using pipe '|'

I am trying to break a string b = "x+yi" into a two integers x and y.

This is my original answer.
Here I removed trailing 'i' character with substring method.

int Integerpart = (int)(new Integer(b.split("\\+")[0]));
int Imaginary = (int)(new Integer((b.split("\\+")[1]).
substring(0, b.split("\\+")[1].length() - 1)));

But I found that the code below just works same.
Is there something special with '|'? I looked up documentation and many other questions but I couldn't find the answer.

int x = (int)(new Integer(a.split("\\+|i")[0]));
int y = (int)(new Integer(a.split("\\+|i")[1]));

Answer Source

You can use the given link for understanding of How Delimiters Works.

How do I use a delimiter in Java Scanner?

Another alternative Way

You can use useDelimiter(String pattern) method of Scanner class. The use of useDelimiter(String pattern) method of Scanner class. Basically we have used the String semicolon(;) to tokenize the String declared on the constructor of Scanner object.

There are three possible token on the String “Anne Mills/Female/18″ which is name,gender and age. The scanner class is used to split the String and output the tokens in the console.

import java.util.Scanner;

 * This is a java example source code that shows how to use useDelimiter(String pattern)
 * method of Scanner class. We use the string ; as delimiter
 * to use in tokenizing a String input declared in Scanner constructor

public class ScannerUseDelimiterDemo {

    public static void main(String[] args) {

        // Initialize Scanner object
        Scanner scan = new Scanner("Anna Mills/Female/18");
        // initialize the string delimiter
        // Printing the delimiter used
        System.out.println("The delimiter use is "+scan.delimiter());
        // Printing the tokenized Strings
        // closing the scanner stream

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download