我正在尝试拆分以下内容,我需要通过函数 strtok 拆分它并且我想获得值 1.2597,请注意 Down 是一个可以更改的动态词。我知道在这种情况下,我可以使用空格作为分隔符,并获得作为货币的值 [1],但我该如何处理它。
CCY 1.2597 下跌 0.0021(0.16%) 14:32 SGT [44]
这应该这样做:
char *first = strtok(string, ' ');
char *second = strtok(0, ' ');
如果要将数字转换为 afloat
或double
也可以使用sscanf
:
char tmp[5];
float number;
sscanf(string, "%s %f", tmp, &number);
或者只是sscanf
在您获得的数字令牌上使用strtok
.
您可以使用Boost.Regex轻松安全地完成此任务:
// use a regular expression to extract the value
std::string str("CCY 1.2597 Down 0.0021(0.16%) 14:32 SGT [44]");
boost::regex exp("CCY (\\d+\\.\\d+)");
boost::match_results<std::string::const_iterator> match;
boost::regex_search(str, match, exp);
std::string match_str(res[1].first, res[1].second)
// convert the match string to a float
float f = boost::lexical_cast<float>(match_str);
std::cout << f << std::endl;
对该函数的一系列调用将 str 拆分为标记,这些标记是由作为定界符一部分的任何字符分隔的连续字符序列。
例子:
char str[] = "now # is the time for all # good men to come to the # aid of their country";
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}
输出:
result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country"