Java Reference
In-Depth Information
Splitting and Joining Strings
It is often useful to split a string around a specified delimiter and join multiple strings into one string using a specified
delimiter.
Use the
split()
method to split a string into multiple strings. Splitting is performed using a delimiter.
The
split()
method returns an array of
String
. You will learn about arrays in Chapter 15. However, you will use
it in this section just to complete the operations of strings.
■
the
split()
method takes a regular expression that defines a pattern as a delimiter. i will discuss regular
expressions in Chapter 14.
Note
String str = "AL,FL,NY,CA,GA";
// Split str using a comma as the delimiter
String[] parts = str.split(",");
// Print the the string and its parts
System.out.println(str);
for(String part : parts) {
System.out.println(part);
}
AL,FL,NY,CA,GA
AL
FL
NY
CA
GA
Java 8 adds a
static join()
method to the
String
class that joins multiple strings into one string. It is
overloaded.
String join(CharSequence delimiter, CharSequence... elements)
•
String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
•
The first version takes a delimiter and a sequence of strings to be joined. The second version takes a delimiter
and an
Iterable
, for example, a
List
or
Set
. The following snippet of code uses the first version to join some strings:
// Join some strings using a comma as the delimiter
String str = String.join(",", "AL", "FL", "NY", "CA", "GA");
System.out.println(str);
AL,FL,NY,CA,GA