Serializar e desserializar array de string
Fornecemos uma array de string e temos que serializar a array de string e desserializar a string serializada.
Exemplos:
Input : "geeks", "are", "awesome" Output : Serialized String : 5~geeks3~are7~awesome Deserialized String : geeks are awesome Input : "hello", "guys", "whats", "up!!!" Output : Serialized String : 5~hello4~guys5~whats5~up!!! Deserialized String : hello guys whats up!!!
Serialização : faça a varredura de cada elemento em uma string, calcule seu comprimento e acrescente uma string e um separador ou deliminador de elemento (esse delimitador não deve estar presente na string). Acrescentamos o comprimento da string para sabermos o comprimento de cada elemento.
Função desserializada: Encontre a posição do delimitador e, a partir da posição + 1 até o comprimento da palavra, armazenamos em uma array como um único elemento.
// CPP program to serialize and
// deserialize the array of string
#include<iostream>
using namespace std;
// Function to serialized the array of string
string serialize(string str[], int ln)
{
string temp = "";
for (int i=0; i<ln; i++)
{
int ln = str[i].length();
temp.push_back('0' + ln);
temp = temp + "~" + str[i];
}
return temp;
}
// Function to deserialize the string
void deserialized(string str, string deserialize[], int ln)
{
int len, pos=0;
string temp = "";
int i = 0;
while(pos>-1)
{
pos = str.find("~", pos+1);
if(pos>0)
{
len = str[pos-1] - 48;
temp.append(str, pos+1, len);
deserialize[i++] = temp;
temp = "";
}
}
}
// Driver function
int main()
{
string str[] = {"geeks", "are", "awesome"};
int ln = sizeof(str)/sizeof(str[0]);
string serializedstr = serialize(str, ln);
cout << "Serialized String : " << serializedstr <<endl;
string deserialize[ln];
deserialized(serializedstr,deserialize,ln);
cout << "Deserialized String : ";
for(int i=0; i<ln; i++)
cout << deserialize[i] << " ";
return 0;
}
Saída:
Serialized String : 5~geeks3~are7~awesome Deserialized String : geeks are awesome
Referências:
1. https://stackoverflow.com/questions/13271503/converting-array-string-to-string-and-back-in-java
2. https://www.careercup.com/question?id=5684077627703296
Este artigo foi contribuído por Rishabh Jain . Se você gosta de GeeksforGeeks e gostaria de contribuir, você também pode escrever um artigo usando contribute.geeksforgeeks.org ou enviar o seu artigo para contribute@geeksforgeeks.org. Veja o seu artigo na página principal do GeeksforGeeks e ajude outros Geeks.
Escreva comentários se encontrar algo incorreto ou se quiser compartilhar mais informações sobre o tópico discutido acima.
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva