2013-05-27 134 views

回答

0

使用

str.split(";"); 

像這樣把它放進一個數組:

String str = ":One;Two:Three;Four:Five;Six:Seven;"; 
String[] foo = str.split(";"); 
+0

不回答這個問題 - OP使用2個不同的分隔符。 – wattostudios

+0

對不起,我忽略了這一點。我會編輯它.. – Dropout

1

一個可能的解決方案是:

str1=str.split(":"); 

在此之後,對於陣列STR1中的每個成員:

str1[x].split(";"); 
1

構建形式的正則表達式

first|second|third 

然後使用字符串的分割()方法通過任何到文本分割分隔符。

所以使用

String [] tokens = str.split(":|;"); 
-1

你不能得到你想要什麼。

str定義爲string並且您希望它是array

您需要使用其他變量才能獲得結果。使用str.split(":|;")功能,結果存儲在String[] result

String[] result = str.split(":|;"); 
+1

爲什麼downvote? –

+0

其實 - 重讀OP的Q.我剛剛做了,現在就得到它:: doh :: –

4

你可以這樣做:

String [] tokens = str.replaceAll(";\\w*:?",":").split(":"); 

第一部分去掉的話你不需要(二,四......)第二部分分裂其餘的部分。請注意,在結果(tokes[0]]第一個項目是空的,按您的規範

例:

public static void main(String[] args) { 
    String str = ":One;Two:Three;Four:Five;Six:Seven;"; 
    String [] tokens = str.replaceAll(";\\w*:?",":").split(":"); 
    for (int i = 0; i < tokens.length; i++) { 
     System.out.println("token[" + i + "] = " + tokens[i]); 
    } 
} 

打印

token[0] = 
token[1] = One 
token[2] = Three 
token[3] = Five 
token[4] = Seven 
+0

nm,我重讀了Q ... :: doh :: –

+1

你也可以嘗試用這種方式來取代第一個空的字符串'replaceAll(「^:|; $ |; \\ w *(?= :)」,「」)' – Pshemo

4

希望這將幫助你

String str = ":One;Two:Three;Four:Five;Six:Seven;" 
    str=str.replace(":",","); 
    str=str.replace(";",","); 

    String [] tokens = str.split(","); 

    token[1]="one"; 
    token[3]="three"; 
    token[5]="five"; 
    token[7]="seven"; 
相關問題