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;
String lastName = sampleStringArray;
String city = sampleStringArray;
String state = sampleStringArray;
Sample Java String Split Output: