经常需要用java拆分字符串如1,2,3,4 tom,jim,andy,han
package com.java.lang;
public class StringSp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
java.lang.String a = "my name is yuexiaosheng my blog is java-er.com";
// java.lang.String 的字符串拆分算法
String[] arr = a.split(" ");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " " + arr[i]);
}
String b = "green|red|blue|black";
// java.lang.String 的字符串拆分算法
arr = b.split("|");
System.out.println("拆分暗礁-------------------------------------------");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " " + arr[i]);
}
System.out.println("拆分暗礁-------------------------------------------");
arr = b.split("\\|");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " " + arr[i]);
}
}
}
0 my
1 name
2 is
3 yuexiaosheng
4 my
5 blog
6 is
7 java-er.com
拆分暗礁-------------------------------------------
0
1 g
2 r
3 e
4 e
5 n
6 |
7 r
8 e
9 d
10 |
11 b
12 l
13 u
14 e
15 |
16 b
17 l
18 a
19 c
20 k
拆分暗礁-------------------------------------------
0 green
1 red
2 blue
3 black
结论部分字符串需要转义,否则按空计算 会把字符一个个拆开。