在Java中,可以使用String类的split()方法来分割字符串。split()方法接受一个正则表达式作为参数,并根据该正则表达式将字符串分割成一个字符串数组。以下是一些使用split()方法的示例:
String str = "Hello,World,Java";
String[] words = str.split(","); // 使用逗号分割字符串
for (String word : words) {
System.out.println(word);
}
String str = "Hello1World2Java3";
String[] words = str.split("[123]"); // 使用1、2、3分割字符串
for (String word : words) {
System.out.println(word);
}
String str = "Hello, World! How are you?";
String[] words = str.split(", |\\s+|\\?"); // 使用逗号、空格和问号分割字符串
for (String word : words) {
System.out.println(word);
}
注意:split()方法返回的字符串数组中可能包含空字符串。例如,当字符串以分隔符开头或结尾时,或者当两个分隔符相邻时。在这种情况下,可以使用Arrays.asList()方法将数组转换为列表,然后使用List的removeIf()方法删除空字符串。
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String str = ",Hello,World,";
String[] words = str.split(",");
List<String> wordList = Arrays.asList(words);
wordList.removeIf(String::isEmpty); // 删除空字符串
for (String word : wordList) {
System.out.println(word);
}
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。