dcsimg
 

Java: Using the Split Method on Strings

Wednesday May 5th 2021 by MS Sridhar
Article Image

This Java programming tutorial shows you how to use the split method to “split” a string that has a delimiter using the Java split method.

This Java programming tutorial shows you how to use the split method to “split” a string that has a delimiter, such as a semi-colon, comma, or colon. We will be using the Java split method on a String Class to show how this works.

This method can also be enhanced with a RegEx, which can yield interesting results with a complex string.

Here is a code sample showing how to use the split method in Java:

*/

public class UsingSplit{

	public static void main(String []args){
		UsingSplit usingSplit = new UsingSplit();
		usingSplit.proceed();
	}

	private void proceed()
	{
	    String splitByChar = ":";
	    String completeString = "One:Two:Three:Four:Five";

        String splitStringArr[] = completeString.split(splitByChar);
        
        System.out.println("Elements after split.");
        for (int i=0; i < splitStringArr.length; i++)
        {
            System.out.println(splitStringArr[i]);        
        }
	}
}

/*

This is the output you can expect when using Java’s split method on a String Class:

$java UsingSplit
Elements after split.
One
Two
Three
Four
Five
Home
Mobile Site | Full Site