Alex Rivera | Logout

Converting array string to string and back in Java

Asked 2012-11-07T14:13:44.490
11

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:

  1. Append all the strings next to each other, for example like this: String[] a = {"lala", "exe", "a"} into String b = "lalaexea"

  2. 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!

Edit
Report

1 Answer

0

I would use the symbol between the words to later use the String#split method to get the String back. Based in your $ symbol example, it would be

public String mergeStrings(String[] ss) {
    StringBuilder sb = new StringBuilder();
    for(String s : ss) {
        sb.append(s);
        sb.append('$');
    }
    return sb.toString();
}

public String[] unmergeStrings(String s) {
    return s.split("\\$");
}

Note that in this example, I add a double \ before the $ symbol because the String#split method receives a regular expression as parameter, and the $ symbol is a special character in regex.

public String processData(String[] ss) {
    String mergedString = mergeStrings(ss);
    //process data...
    //a little example...
    for(int i = 0; i < mergedString.length(); i++) {
        if (mergedString.charAt(i) == '$') {
            System.out.println();
        } else {
            System.out.print(mergedString.charAt(i));
        }
    }
    System.out.println();
    //unmerging the data again
    String[] oldData = unmergeStrings(mergedString);
}

In order to support any character in your String[], it would be better to set not a single character as separator but instead another String. The methods would turn into this:

public static final String STRING_SEPARATOR = "@|$|@";
public static final String STRING_SEPARATOR_REGEX = "@\\|\\$\\|@";

public String mergeStrings(String[] ss) {
    StringBuilder sb = new StringBuilder();
    for(String s : ss) {
        sb.append(s);
        sb.append(STRING_SEPARATOR);
    }
    return sb.toString();
}

public String[] unmergeStrings(String s) {
    return s.split(STRING_SEPARATOR_REGEX);
}
answered 2012-11-07T14:19:41.283

Your Answer