-
-
Save thiagomoretto/1424047 to your computer and use it in GitHub Desktop.
String[] Encode/Decode (my attempt)
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
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