我们已经给出了一个字符串数组,我们必须序列化字符串数组,并反序列化序列化序列化的字符串。 例如:
null
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!!!
系列化 :扫描字符串中的每个元素,计算其长度,并将其附加到字符串和元素分隔符或删除器(该删除器不应出现在字符串中)。我们附加字符串的长度,以便知道每个元素的长度。
反序列化函数: 找到删除器的位置,然后从位置+1到单词长度,我们将其作为单个元素存储在一个数组中。
// 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; } |
输出:
Serialized String : 5~geeks3~are7~awesome Deserialized String : geeks are awesome
参考资料: 1. https://stackoverflow.com/questions/13271503/converting-array-string-to-string-and-back-in-java 2. https://www.careercup.com/question?id=5684077627703296
本文由 里沙布·贾因 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END