How to split a string in java or split by period/dot in java?

To split a string in java into multiple Strings given the delimiter that separates them use java method split(regex). The returned object is an array which contains the split Strings.

We can also pass a limit parameter split(regex,limit) to the number of elements in the returned array. If we pass 0 as a limit, then the method will behave as if we didn’t pass any limit, returning an array containing all elements that can be split using the passed delimiter.

1. Split String with any delimiter


/****************************************************************************************
 * Created on 06-2019 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java;

/**
 * Created by https://kodehelp.com
 * Date: 06/22/2019
 */
public class SplitStringInJava {

	public static void main(String[] args) {
		
		String phone = "132-476-9483"; // replace this with your string
		String[] output = phone.split("-");//replace this with your delimiter
		for(String s: output)
		System.out.println(s);
		
	}

}
OUTPUT
132
476
9483

2. Split string with any delimiter and limit


/****************************************************************************************
 * Created on 06-2019 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java;

/**
 * Created by https://kodehelp.com
 * Date: 06/22/2019
 */
public class SplitStringInJava {

	public static void main(String[] args) {
		
		String phone = "132-476-9483"; // replace this with your string
		String[] output = phone.split("-",2);//replace this with your delimiter
		for(String s: output)
		System.out.println(s);
		
	}

}
OUTPUT
132
476-9483

3. Split string with period or dot as delimiter


Note: To split a String with the period or dot and this character is a special character in the regex, you have to escape it either with a double backslash \\. or uses the Pattern.quote method.

/****************************************************************************************
 * Created on 06-2019 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java;

/**
 * Created by https://kodehelp.com
 * Date: 06/22/2019
 */
public class SplitStringInJava {

	public static void main(String[] args) {
		
		String phone = "132.476.9483"; // replace this with your string
		String[] output = phone.split("\\.");//replace this with your delimiter
		for(String s: output)
		System.out.println(s);
		
	}

}
OUTPUT
132
476
9483
References:

Please Post Your Comments & Reviews

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