Java String split() Method Example

1. Introduction

The String.split() method in Java is used to split a string around matches of the given regular expression. This method returns an array containing the substrings split from the string. It is widely used for parsing data, processing text, and formatting output. This tutorial will demonstrate how to use the split() method effectively.

Key Points

- split() divides a string based on a regular expression.

- It returns an array of strings.

- Useful for extracting data or manipulating the format of strings.

2. Program Steps

1. Declare a string to be split.

2. Split the string using a delimiter.

3. Iterate through the array of split strings and print each element.

3. Code Program

public class StringSplitExample {
    public static void main(String[] args) {
        // String to be split
        String str = "apple,banana,cherry";
        // Split string by commas
        String[] fruits = str.split(",");
        // Print each element from the result array
        System.out.println("List of fruits:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output:

List of fruits:
apple
banana
cherry

Explanation:

1. String str = "apple,banana,cherry": Declares and initializes a String variable str.

2. String[] fruits = str.split(","): Splits str into an array fruits using a comma , as the delimiter.

3. The loop iterates over fruits and prints each element, which are the substrings 'apple', 'banana', and 'cherry'.


Comments