2012-11-30 34 views
1

假設我有兩個字符串用分隔符「加入」。Implode /爆炸一個字符串:你會建議什麼逃避計劃?

 
String s1 = "aaa", s2 = "bbb"; // input strings 
String s3 = s1 + "-" + s2; // join the strings with dash 

我可以使用s3.split("-")得到s1s2。現在,如果s1s2包含破折號?假設s1s2可能包含任何ASCII可打印,我不想使用不可打印的字符作爲分隔符。

什麼樣的轉義你會建議在這種情況下?

+0

你定界符真正需要的是唯一的或者容易discerne根據上下文。如果選擇短劃線作爲分隔符,則需要確定一些規則,以指示短劃線是分隔符還是短劃線。你可以使用某種類型的轉義代碼,或者說當短劃線在引號之間時,它不是分隔符。如果你可以使用它,@ user714965提供的OpenCSV解決方案似乎是個不錯的主意。或者把你的分隔符改爲像||這樣的其他東西或其他不太可能出現在您的字符串中的其他內容。 –

回答

4

如果我可以定義格式,分隔符等,我會使用OpenCSV並使用它的默認值。

0

爲什麼不把這些字符串存儲在一個數組中,並且每次要將它們顯示給用戶時都要用短劃線連接它們?

+0

假設它超出範圍:) – Michael

1

您可以使用不常見的字符序列,例如;:;作爲分隔符而不是單個字符。

+0

如果這個序列確實出現在「加入」字符串中,該怎麼辦? – Michael

+1

這將需要逃脫。假設你使用短劃線作爲分隔符。要在不破壞分割的情況下在最終字符串中顯示短劃線字符,可以鍵入類似'\ -'的內容。要在最後一個字符串中顯示'\ -',你可以通過轉義轉義字符來輸入'\\ - '等等。但這並非沒有缺陷。查看http://en.wikipedia.org/wiki/Delimiter#Solutions – Cryszon

1

這裏是另一個可行的解決方案,即不使用分離器,但加入的內爆字符串結尾的字符串的長度要能後重新爆發,:

public static void main(String[] args) throws Exception { 
    String imploded = implode("me", "and", "mrs.", "jones"); 
    System.out.println(imploded); 
    String[] exploded = explode(imploded); 
    System.out.println(Arrays.asList(exploded)); 
} 

public static String implode(String... strings) { 
    StringBuilder concat = new StringBuilder(); 
    StringBuilder lengths = new StringBuilder(); 
    int i = 0; 
    for (String string : strings) { 
     concat.append(string); 
     if (i > 0) { 
      lengths.append("|"); 
     } 
     lengths.append(string.length()); 
     i++; 
    } 
    return concat.toString() + "#" + lengths.toString(); 
} 

public static String[] explode(String string) { 
    int last = string.lastIndexOf("#"); 
    String toExplode = string.substring(0, last); 
    String[] lengths = string.substring(last + 1).split("\\|"); 
    String[] strings = new String[lengths.length]; 
    int i = 0; 
    for (String length : lengths) { 
     int l = Integer.valueOf(length); 
     strings[i] = toExplode.substring(0, l); 
     toExplode = toExplode.substring(l); 
     i++; 
    } 
    return strings; 
} 

打印:

meandmrs.jones#2|3|4|5 
[me, and, mrs., jones]