vendredi 20 février 2015

Dumping an string array in single string

Given an array of strings A of variable length, the task is to save the array in a string DUMP and then to recreate the same array from DUMP. The strings in the input array A can contain any printable characters.


The first thought came to my mind was the trivial one, i.e. append A[i]'s in the string DUMP, separated by some separator eg '\'. But if any string has the separator character as one of its character, then recreation will fail.


The next idea was to escape the separator (say '\') if it exists in some string. If \ is in some string, then replace it with \\, if \\ exists in string, then replace with \\\ and so on. So during recreation, if only one continuous \ is encountered, then it is a separator otherwise it is part of some string. But this fails if '\\' comes in end of some string i.e. A[6] = 'abc\', A[7] = 'de' will be stored as abc\\\de.


Although this is easy if the length of the strings in array A are also saved in the DUMP string. But I couldn't think of any way just by manipulating characters and without using any other string property. Is there any algorithm to do the same?


Aucun commentaire:

Enregistrer un commentaire