JavaDevNotes.com

Java Split String Into Array Examples

Strings and Arrays are two of the most popular data type in Java and in other popular language. String are able to represent a series of characters that is viewed as a single entity. While arrays are used to hold multiple values in the most simple way. But how do we convert a String like "One,Two,Three" into an array splitting into 3 different words or string? Below are some examples on in Java on how to split String into Array.

Split String Into Array Using Split()

The Java class contains a simple method that can help us Split Strings and return an array. below is the syntax:

public String[] split(String regex)

For example, if we have a String that contains fruits separated by comma:
String mySampleString = "Apple,Banana,Pineapple";
The Split() method of the String can be used to convert it to an array with three items containing the individual fruit. Below is an example:
String mySampleString = "Apple,Banana,Pineapple";
String[] fruits = mySampleString.split(",");
System.out.println("The number of fruits is: " + fruits.length);
for (String fruit : fruits) {
   System.out.println(fruit);
}

The output will be:

The number of fruits is: 3
Apple
Banana
Pineapple

We can do this because there is a common separator which is comma, and we supplied it by passing comma as parameter to the split() method. It uses the separator to determine which are the items of the resulting array.

We can put a maximum number of items in the resulting array if we want to. For example, here is the modified version of the code

String mySampleString = "Apple,Banana,Pineapple";
String[] fruits = mySampleString.split(",", 2);
System.out.println("The number of fruits is: " + fruits.length);
for (String fruit : fruits) {
   System.out.println(fruit);
}
We supplied the parameter 2 to mean that we want maximum of 2 items in the resulting array. The result will be:
The number of fruits is: 2
Apple
Banana,Pineapple
The caveat here is that the last element will contain the rest of the String after splitting the the previous items. For more related examples, visit this post about Splitting String into ArrayList and this post about Java String's split() method.

Support my blog by buying some of my t-shirt, mug, and phone case designs!
                   

String Tutorials And Examples