字符串分割

public int getCount(String str,String sign){

//查找某一字符串中str,特定子串s的出現次數

if(str==null) return 0;

StringTokenizer s=new StringTokenizer(str,sign);

return s.countTokens();

}

public String[] getArray(String str,String sign){

//按特定子串s爲標記,將子串截成數組。

int count=getCount(str,sign);

int j=0;

String[] arr=new String[count];

for(int i=0;i<count;i++){

if(str.indexOf(sign)!=-1){

j =str.indexOf(sign);

arr[i]=str.substring(0,j);

str =str.substring(j+1);

}else{

arr[i]=str;

}

}

return arr;

}

public String[] split(String regex, int limit)根據匹配給定的正則表達式來拆分此字符串。SPLIT參數支持正則表達式, s.split("\\|+");//以|或多個|做爲分割符號分割字符串,如果表達式不匹配輸入的任何部分,則結果數組只具有一個元素,即此字符串。limit 參數控制模式應用的次數,因此影響結果數組的長度。如果該限制 n 大於 0,則模式將被最多應用 n - 1 次,數組的長度將不會大於 n,而且數組的最後項將包含超出最後匹配的定界符的所有輸入。如果 n 爲非正,則模式將被應用儘可能多的次數,而且數組可以是任意長度。如果 n 爲零,則模式將被應用儘可能多的次數,數組可有任何長度,並且結尾空字符串將被丟棄。

split(String regex)中將默認第二個參數爲0,會取消掉最後的空字符串。

public class SplitTest {

public static void main(String[] args) {

String[] num = null; //這裏不用創建數組,split 方法會幫你創建大小合適的數組

String sLine="101494|360103660318444|2008/06/17|周潤英|1292.0|3085.76|2778.28|912.91|106.0|||";

num = sLine.split("\\|", -1);

for (int i = 0; i < num.length; ++i) {

System.out.println(i + ": " + num[i]);

}}}

結果

0: 101494

1: 360103660318444

2: 2008/06/17

3: 周潤英

4: 1292.0

5: 3085.76

6: 2778.28

7: 912.91

8: 106.0

9:

10:

11:

public static String[] Split(String str, String sp) {// str要分割的字符串; sp分隔符;return 分割後的字符串;
StringTokenizer st = new StringTokenizer(str, sp);
String strSplit[];
try {
int stLength=st.countTokens();//獲取分割後的數量
if(stLength<=1) { return null; }
strSplit=new String[stLength];
int i=0;
while (st.hasMoreTokens()) {
strSplit[i]=st.nextToken().toString();
i++;
} }
catch(Exception e) { return null; }
return strSplit;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章