我建议使用"string::find()"和"string::substr()"的组合。
或者一些正则表达式的东西,但我认为这需要通过标准库。
例子:
std::string::size_type n;
std::string key;
std::string value;
n = line.find(':');
key = line.substr( 0, n );
value = line.substr( n+1 );
然后可能需要从白色字符中去除键和值。我不会涵盖它,因为关于如何做到这一点的问题和答案很少。例如:
- C++ 中与 Python 的 strip() 类似的函数?
- 修剪 std::string 的最佳方法是什么?
编辑:
完整的示例代码split.cpp
:
/// TRIMMING STUFF
// taken from https://stackoverflow.com/a/217605/1133179
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); }
/// ~~~ TRIMMING STUFF ~~~
#include <string>
#include <iostream>
int main(){
std::string::size_type n;
std::string key;
std::string value;
std::string line = "system type : Atheros AR7241 rev 1";
n = line.find(':');
key = line.substr( 0, n );
value = line.substr( n+1 );
std::cout << "line: `" << line << "`.\n";
std::cout << "key: `" << key << "`.\n";
std::cout << "value: `" << value << "`.\n";
/// With trimming
std::cout << "{\n "json" : [{ \"" << trim(key) << "\" : \"" << trim(value) << "\" }]\n}\n";
}
执行:
luk32:~/projects/tests$ g++ ./split.cpp
luk32:~/projects/tests$ ./a.out
line: `system type : Atheros AR7241 rev 1`.
key: `system type `.
value: ` Atheros AR7241 rev 1`.
{
"json" : [{ "system type" : "Atheros AR7241 rev 1" }]
}
我认为没关系。