這裏是另一個可行的解決方案,即不使用分離器,但加入的內爆字符串結尾的字符串的長度要能後重新爆發,:
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]
你定界符真正需要的是唯一的或者容易discerne根據上下文。如果選擇短劃線作爲分隔符,則需要確定一些規則,以指示短劃線是分隔符還是短劃線。你可以使用某種類型的轉義代碼,或者說當短劃線在引號之間時,它不是分隔符。如果你可以使用它,@ user714965提供的OpenCSV解決方案似乎是個不錯的主意。或者把你的分隔符改爲像||這樣的其他東西或其他不太可能出現在您的字符串中的其他內容。 –