To split a string in Java, you can use the split
method of the String
class and specify the delimiter character or pattern to use for splitting.
Here's an example of how you can split a string on a single character:
String s = "apple,banana,cherry"; String[] parts = s.split(","); for (String part : parts) { System.out.println(part); }
This code will split the string s
on the comma character, and print the resulting substrings to the console. The output will be:
apple banana cherry
You can also use a regular expression as the delimiter pattern to split the string on multiple characters or a more complex pattern. For example, to split the string on any sequence of one or more whitespace characters, you can use the following code:
String s = "apple banana cherry"; String[] parts = s.split("\\s+"); for (String part : parts) { System.out.println(part); }
This code will split the string s
on any sequence of one or more whitespace characters, and print the resulting substrings to the console. The output will be:
apple banana cherry
By default, the split
method will return an array containing all the substrings that were found. You can also specify a limit parameter to limit the number of substrings that are returned. For example, to split the string into at most two substrings, you can
public class Lautturi { public static void main(String[] args) { String s = "apple banana cherry"; String[] parts = s.split("\\s+",2); for (String part : parts) { System.out.println(part); } } }
output:
apple banana cherry