Split string in Java

You can split a string into an array of substrings using the split() method of the String class. The split() method takes a regular expression as a parameter and returns an array of substrings.

Here's an example code snippet that demonstrates how to split a string into an array of substrings based on a delimiter (in this case, a comma):

public class SplitStringExample { public static void main(String[] args) { String input = "apple,banana,orange"; String[] fruits = input.split(","); for (String fruit : fruits) { System.out.println(fruit); } } }

In this example, we first define a string called input that contains three fruit names separated by commas. We then call the split() method on this string with a comma as the delimiter. The split() method returns an array of substrings that we store in a string array called fruits. Finally, we iterate over the fruits array using a for loop and print each fruit name to the console.

apple banana orange

Note that the split() method also supports regular expressions as delimiters. For example, to split a string based on any whitespace character (including spaces, tabs, and newlines), you can pass the regular expression \s+ as the delimiter.