来个c/C++大神聊聊

店长大人 2.45m2021-07-28197 次点击
需要的c++函数做字符串切割。
来个有实际应用的大神聊聊。
收藏 ♥ 感谢
九年吃菜粥 33.25m 2021-07-28 
说具体一些啊,倒是说需求和效果啊
店长大人 2.45m 2021-07-28 
有个string字符串:“+CMGLOC:102701.328,3639.6511N,11653.4980E,11.3,-4.4,2,0.00,0.0,0.0,240721,03”,使用C/C++语言,以“:”“,”,还有“N”,“E”将字符串进行分割,取出对用的子字符串。以备后用。
九年吃菜粥 33.25m 2021-07-28  ♥ 1
@店长大人
普通分割做法我就不详细说,百度一搜都有,自己用循环写也不难,先用逗号当分隔符,再对特殊项如 +CMGLOC:102701.328 用冒号分隔,再塞进源数组,字母N E也以此类推

也可以正则表达式,^(.*?):(.*?),(.*?)N,(.*?)E,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)$
这个表达式匹配的第一项是 +CMGLOC,第二项是 102701.328,以此类推
九年吃菜粥 33.25m 2021-07-28 
@店长大人

普通做法
#include <iostream>
#include <vector>

using namespace std;

vector<string> split(string str, string pattern) {‌
// 复制自百度
string::size_type pos;
vector<string> result;
str += pattern;// 扩展字符串以方便操作
int size = str.size();
for (int i = 0; i < size; i++) {‌
pos = str.find(pattern, i);
if (pos < size) {‌
string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}

vector<string> my_split(string str) {‌
vector<string> result;
vector<string> result_1 = split(str, ",");
vector<string> result_2 = split(result_1[0], ":");
for (auto r:result_2)
result.push_back(r);
for (unsigned int i = 1;i<result_1.size();++i)
result.push_back(result_1[i]);
return result;
}

int main() {‌
string S = "+CMGLOC:102701.328,3639.6511N,11653.4980E,11.3,-4.4,2,0.00,0.0,0.0,240721,03";
vector<string> result = my_split(S);
for (auto s:result)
cout << s << endl;
return 0;
}
九年吃菜粥 33.25m 2021-07-28  ♥ 1
@店长大人
正则表达式方法

#include <iostream>
#include <regex>

using namespace std;

vector<string> get_params(string str){‌
vector<string> result;
regex base_regex("^(.*?):(.*?),(.*?)N,(.*?)E,(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)$");
smatch base_match;
if (regex_match(str, base_match, base_regex)) {‌
if (base_match.size()>1)
for (unsigned int i = 1; i < base_match.size(); ++i)
result.push_back(base_match[i]);
}
return result;
}

int main() {‌
string S = "+CMGLOC:102701.328,3639.6511N,11653.4980E,11.3,-4.4,2,0.00,0.0,0.0,240721,03";
vector<string> result=get_params(S);
for (auto s:result)
cout << s << endl;
return 0;
}
店长大人 2.45m 2021-07-28 
@九年吃菜粥,非常感谢大神的回复。很厉害,试过了,确实可以,多谢🙏多谢。辛苦了。

登录注册 后可回复。