public class test1 { public static void main(String[] args){ String[] s="ABCDE".split(" "); for(int i=0;i<s.length;i++) System.out.println(i+s[i]); } } //输出: //0ABCDE
public class test1 { public static void main(String[] args){ String[] s="ABCDE".split(""); for(int i=0;i<s.length;i++) System.out.println(i+s[i]); } } //输出: //0 //1A //2B //3C //4D //5E
与上一段程序比较
public class test1 { public static void main(String[] args){ String[] s=" ABCDE".split(" "); for(int i=0;i<s.length;i++) System.out.println(i+s[i]); } } //输出: //0 //1ABCDE
字符间只有一个空格
String str = "关键词1 关键词2 关键词3"; String[] words = str.split(" "); for(String word : words){ System.out.println(word); }
String str = "关键词1 关键词2 关键词3"; String[] words = str.split("\\s+"); for(String word : words){ System.out.println(word); }
public class test1 { public static void main(String[] args){ String str = "111,222,333 444 555"; String regex = ",|,|\\s+"; String strAry[] = str.split(regex); for (int i = 0; i < strAry.length; i++) { System.out.println("i="+i+" Val="+strAry[i]); } } } //输出: //i=0 Val=111 //i=1 Val=222 //i=2 Val=333 //i=3 Val=444 //i=4 Val=555