Skip to content

Instantly share code, notes, and snippets.

@chuanying
Created September 10, 2013 05:30
Show Gist options
  • Save chuanying/6505331 to your computer and use it in GitHub Desktop.
Save chuanying/6505331 to your computer and use it in GitHub Desktop.
string split.cc 序列化多个字符串, 网络传到另一台机器, 再反序列化他
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stdio.h>
#include <math.h>
using namespace std;
//[len],[value][len],[value]....[-1]
string string_conn(string a, string b) {
stringstream ss;
ss << a.length() << "," << a << b.length() << "," << b << -1;
return ss.str();
}
string string_conn(vector<string> vec) {
stringstream ss;
for (int i = 0; i < vec.size(); ++i) {
ss << vec[i].length() << "," << vec[i];
}
ss << -1;
return ss.str();
}
vector<string> string_split(string s) {
vector<string> vec;
int pos = 0;
while (pos < s.length()) {
int p = s.find(',', pos);
if (p == string::npos) {
break;
}
int len = atoi(s.substr(pos, p - pos).c_str());
if (len < 0) {
break;
}
vec.push_back(s.substr(p + 1, len));
pos = p + 1 + len;
}
return vec;
}
int main(int argc, char* argv[]) {
string ans = string_conn(vector<string>(3, "abc"));
cout << ans << endl;
vector<string> res = string_split(ans);
for (int i = 0; i < res.size(); ++i) {
cout << "[" << res[i] << "]" << endl;
}
return 0;
}
@chuanying
Copy link
Author

协议是这么定的: 先传长度, 再传一个分隔符(,) 再传内容. 网络传输的时候, 不知道如何结束, 后面没有数据了, 就传一个-1进去. 不是二进制的-1, 而是字符串的"-1", 所以不用考虑大小端的问题.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment