说你有
char *= "name:454";解析名称和数字的最佳方法是什么?
std:字符串id等于"name";
双倍d等于454;
STL,请不要提速。
发布于 2009-04-06 19:41:17
#include <iostream>
#include <sstream>
#include <string>
int main() {
/* output storage */
std::string id;
double d;
/* convert input to a STL string */
std::string s("name:454");
size_t off = std::string::npos;
/* smart replace: parsing is easier with a space */
if ((off = s.find(':')) != std::string::npos) { // error check: all or none
s = s.replace(off, 1, 1, ' ');
std::istringstream iss(s);
iss >> id >> d;
std::cout << "id = " << id << " ; d = " << d << '\n';
}
return 0;
}不过,我只需要编写自己的解析器或使用C扫描器函数来提高速度。
发布于 2009-04-06 19:30:25
您希望使用':'作为令牌来查看strtok函数。下面是一个示例:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "name:454";
char* c = strtok(str, ":");
while (c != NULL)
{
printf("%s\n", c);
c = strtok(NULL, ":");
}
return 0;
}发布于 2009-04-06 19:34:42
我会使用getline。
示例:http://github.com/lennartkoopmann/scopeport-server/blob/23e3d2e2fede7ced0810deee0aa501a70a4eba40/src/core.cc#L1353
https://stackoverflow.com/questions/722801
复制相似问题