How does Java use the split() function of the String class to split a string by a specified delimiter
In Java, the String class is a very commonly used class that provides many useful methods to handle and Manipulate strings. One of the commonly used methods is the split() function, which can split a string into multiple substrings according to the specified delimiter.
The syntax of the split() function is as follows:
String[] split(String regex)
Among them, regex is a regular expression used to specify the separator.
Here is a simple example that demonstrates how to use the split() function to split a string by spaces:
public class SplitExample { public static void main(String[] args) { String str = "Hello World"; String[] words = str.split(" "); for (String word : words) { System.out.println(word); } } }
The output is:
Hello World
In the above example , we use spaces as delimiters to split the string "Hello World" into two substrings "Hello" and "World".
In addition to simple space delimiters, the split() function also supports the use of other regular expressions as delimiters. Here is an example that demonstrates how to split a string using commas:
public class SplitExample { public static void main(String[] args) { String str = "apple,banana,orange"; String[] fruits = str.split(","); for (String fruit : fruits) { System.out.println(fruit); } } }
The output is:
apple banana orange
In the above example, we have used comma as the separator to split the string "apple,banana,orange" is split into three substrings "apple", "banana" and "orange".
It should be noted that the split() function returns a string array. If you want to get the number of split substrings, you can use the length property of the array.
The above is the introduction and sample code on how to use the split() function of the String class to split a string according to the specified delimiter. Hope this helps!
The above is the detailed content of How to use split() function of String class in Java to split a string by specified delimiter. For more information, please follow other related articles on the PHP Chinese website!