Skip to content

Instantly share code, notes, and snippets.

@ar
Created December 1, 2011 21:15
Show Gist options
  • Save ar/1419936 to your computer and use it in GitHub Desktop.
Save ar/1419936 to your computer and use it in GitHub Desktop.
String[] Encode/Decode
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) {
for (int i = 0; i<s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\\':
case ',' :
sb.append('\\');
break;
}
sb.append(c);
}
}
}
return sb.toString();
}
public static String[] decode (String s) {
List<String> l = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
boolean escaped = false;
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (!escaped) {
switch (c) {
case '\\':
escaped = true;
continue;
case ',':
l.add(sb.toString());
sb = new StringBuilder();
continue;
}
}
sb.append(c);
escaped=false;
}
l.add(sb.toString());
return l.toArray(new String[l.size()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment