public class SplitExample {
public static void main(String[] args) {
// 定义一个字符串,包含多个单词,用空格分隔
String sentence = "Java is fun and easy to learn";
// 使用split()函数,以空格为分隔符将字符串分割成数组
String[] words = sentence.split(" ");
// 输出分割后的结果
for (String word : words) {
System.out.println(word);
}
// 另一个例子:使用逗号作为分隔符
String csv = "apple,orange,banana,grape";
String[] fruits = csv.split(",");
// 输出分割后的结果
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
split() 函数:这是 Java 中 String 类的一个方法,用于根据指定的分隔符将字符串分割成子字符串,并返回一个字符串数组。sentence,并使用空格 " " 作为分隔符来分割这个字符串。分割后,每个单词都被存储在数组 words 中,然后我们遍历并打印每个单词。csv,并使用逗号 "," 作为分隔符来分割这个字符串。分割后,每个水果名称都被存储在数组 fruits 中,然后我们遍历并打印每个水果名称。通过这两个示例,你可以看到 split() 函数可以根据不同的分隔符(如空格、逗号等)来分割字符串。
上一篇:java入门简单小游戏代码
下一篇:java引用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站