Skip to content

Instantly share code, notes, and snippets.

@thiagomoretto
Forked from ar/StringUtil.java
Created December 2, 2011 17:20
Show Gist options
  • Save thiagomoretto/1424047 to your computer and use it in GitHub Desktop.
Save thiagomoretto/1424047 to your computer and use it in GitHub Desktop.
String[] Encode/Decode (my attempt)
import java.util.*;
public class StringUtil {
public static String encode (String[] ss) {
StringBuilder sb = new StringBuilder();
for (String s : ss) {
if (sb.length() > 0)
sb.append(',');
if (s != null)
sb.append(s.replaceAll("\\\\", "\\\\\\\\")
.replaceAll(",", "\\\\,"));
}
return sb.toString();
}
public static String[] decode(String s) {
List<String> l = new ArrayList<String>();
for(String st : s.split("(?<!\\\\),"))
l.add(st.replaceAll("\\\\,", ","));
return l.toArray(new String[l.size()]);
}
public static void main(String[] args) {
// Without nulls
System.out.println("* Without nulls");
System.out.println("Encoded: "+ StringUtil.encode(new String[] {"abc", "xyz", "123,456"}));
System.out.println("Decoded: ");
for(String p : StringUtil.decode("abc,xyz,123\\,456"))
System.out.println(": " + p);
// With nulls
System.out.println("* With nulls");
String encoded = StringUtil.encode(new String[] {"abc", null, "123,456", "String with a \\ in it" });
System.out.println("Encoded: "+ encoded);
System.out.println("Decoded: ");
for(String p : StringUtil.decode(encoded))
System.out.println(": " + p);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment