2013-12-08 228 views
-3
String test = "a,b|c,d|e,f"; 

如何使用.split方法進行分割字符串測試成爲分割字符串

arrayList.get(0); // ans is a 
arrayList.get(1); // ans is c 
arrayList.get(2); // ans is e 

arrayList1.get(0); // ans is b 
arrayList1.get(1); // ans is d 
arrayList1.get(2); // ans is f 
+0

你試過了什麼?試圖找到它們如何分佈在兩個名單上的模式...它不那麼難 – Blub

+0

我已經把它們分成(a,b)(c,d)(e,f) – user2511316

+0

是的,現在你只需要再次拆分它們並將它們分配到兩個列表中;) – Blub

回答

1

您可以使用

for(String pair : text.split("[|]")) { 
    String[] parts = pair.split(",", 2); 
    arrayList.add(parts[0]); 
    arrayList1.add(parts[1]); 
} 
0

試試這個:

String s[] = "a,b|c,d|e,f".split("[,\\|]"); 

這樣,偶數索引(0,2,4)將包含a, c, d和奇數索引(1,3,5)將包含b, d, f。現在創建兩個ArrayList並相應地添加它們。

0

您可以使用\\ W任何非單詞字符分割

test.split("\\W"); 
0

您可以嘗試LIK ethis:

String str[] = "a,b|c,d|e,f".split("[,\\|]"); 
0

這樣做:

split("|"); 

arr[]={"a,b","c,d","e,f"} 

然後,你可以每個字符串分割與split(",");

a1[]={"a","b"} 
a2[]={"c","d"} 
a3[]={"e","f"} 

現在把A1的第一要素,A2,A3在ArrayList和在arrayList1第二。