I have an array String[] in Java, and must first encode/convert it into a String and then further in the code covert it back to the String[] array. The thing is that I can have any character in a string in String[] array so I must be very careful when encoding. And all the information necessary to decode it must be in the final string. I can not return a string and some other information in an extra variable.
My algorithm I have devised so far is to:
-
Append all the strings next to each other, for example like this:
String[] a = {“lala”, “exe”, “a”}
into
String b = “lalaexea” -
Append at the end of the string the lengths of all the strings from String[], separated from the main text by $ sign and then each length separated by a comma, so:
b = “lalaexea$4,3,1”
Then when converting it back, I would first read the lengths from behind and then based on them, the real strings.
But maybe there is an easier way?
Cheers!
If you don’t wanna spend so much time with string operations you could use java serialization + commons codecs like this:
This will return the following output:
If you are using maven, you can use the following dependency for commons codec:
As suggested with base64 (two lines change):
In case of Base64 the result string is shorter, for the code exposed below:
Regarding the times for each approach, I perform 10^5 executions of each method and the result was as follows:
Code used for test: