Answer:
Method 1: '+' to split strings, '\' to transfered symbol.
import java.util.ArrayList;
public class Dumper {
public static void main(String [] args) {
String [] str_array = new String [] {
"a+b", // a+b
"c\\b", // c\b
};
System.out.println("Orig: ");
for(String s : str_array) {
System.out.println(s);
}
String str_serialized = Serialize(str_array);
System.out.println("Serialized: " + str_serialized);
String [] str_deserialized = Deserialize(str_serialized);
System.out.println("Deserialized: ");
for(String s : str_deserialized) {
System.out.println(s);
}
}
static String Serialize(String [] str_arr) {
StringBuilder buf = new StringBuilder();
for(String s : str_arr) {
for(int i=0; i<s.length(); ++i) {
char c = s.charAt(i);
if(c == '+' || c == '\\') {
buf.append('\\');
}
buf.append(c);
}
buf.append('+');
}
return buf.toString();
}
static String [] Deserialize(String str) {
ArrayList<String> str_arr = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
for(int i=0; i<str.length(); ++i) {
char c = str.charAt(i);
if(c == '\\') {
c = str.charAt(i+1);
i++;
buf.append(c);
}
else if(c == '+') {
str_arr.add(buf.toString());
buf = new StringBuilder();
}
else {
buf.append(c);
}
}
return str_arr.toArray(new String [0]);
}
}
No comments:
Post a Comment