public class StringSplitExample {
public static void main(String[] args) {
// 定义一个字符串,包含多个单词,用空格分隔
String sentence = "Java is fun and easy to learn";
// 使用split方法按照空格分割字符串
String[] words = sentence.split(" ");
// 输出分割后的结果
System.out.println("Splitting the sentence by space:");
for (String word : words) {
System.out.println(word);
}
// 使用split方法按照指定字符分割字符串,并限制分割次数
String numbers = "1,2,3,4,5,6";
String[] numberArray = numbers.split(",", 3);
// 输出分割后的结果
System.out.println("\nSplitting the numbers by comma with limit 3:");
for (String num : numberArray) {
System.out.println(num);
}
}
}
split(String regex)
:
split(" ")
表示按照空格进行分割。split(String regex, int limit)
:
limit
参数,分割操作将在达到该限制时停止。例如,split(",", 3)
表示最多分割成 3 个部分。输出结果:
上一篇:java获取服务器ip和端口号
下一篇:java计算两个日期之间的天数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站