Java Data Type How to - Split a String by a substring








Question

We would like to know how to split a String by a substring.

Answer

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.

public class Main {
  public static void main(String[] args) {
    String str = "A,B,C,D";
// w  ww .  j  a v a2  s . c o  m
    // 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);
    }
  }
}

The code above generates the following result.