Home > Tutorial > Java String Split Sample Code

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:

package com.jcd.java.tutorials;

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);
		System.out.println("City="+city);
		System.out.println("State="+state);	
	}

}


Sample Java String Split Output:

First Name=JOHN
Last Name=DOE
City=NEW YORK
State=NY



Java References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot