Java String Split Sample Code

Often times as a Java programmer, you will need to split a string into an array and access each element of the array individually. It’s convenient to append a list of items into a single array and then pass one object to a class or method. The Java sample code below has a list of objects separated by a pipe “|”.

I like to use the pipe as a separator because most of the time it’s a special character that is not used that often. Keep in mind that when using a pipe to separate text, you will need to escape it first using “\\” as seen below in the call to String.split().

  • Method: split()
  • Input: None
  • Return: String[]
  • Description: Splits this string around matches of the given regular expression.

Java String Split Source Code:


public class StringSplit 
	 public static void main( String[] args )
		String sampleString = "JOHN|DOE|NEW YORK|NY|";
		String[] sampleStringArray = sampleString.split("\\|");
		String firstName = sampleStringArray[0];
		String lastName = sampleStringArray[1];
		String city = sampleStringArray[2];
		String state = sampleStringArray[3];
		System.out.println("First Name="+firstName);
		System.out.println("Last Name="+lastName);


Sample Java String Split Output:

First Name=JOHN
Last Name=DOE

Java References:

Add a Comment

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