How to use the split method in Java?
In Java, you can split a string using the split() method. This method takes a string parameter as the delimiter to separate the original string and returns an array of strings.
Here is an example code demonstrating how to use the split() method to split a string.
String str = "Hello, World! This is a sample string.";
// 使用空格分隔字符串
String[] words = str.split(" ");
// 遍历并打印拆分后的字符串数组
for (String word : words) {
System.out.println(word);
}
The output result is:
Hello,
World!
This
is
a
sample
string.
In the above example, we used spaces as separators to split the string. You can use different separators such as commas, periods, etc., according to your needs. Just pass the desired separator as a parameter to the split() method.