Created
December 1, 2011 21:15
-
-
Save ar/1419936 to your computer and use it in GitHub Desktop.
String[] Encode/Decode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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