Chr*_*son 2 c c++ string parsing scanf
我正在解析一个遵循可预测模式的字符串:
例如:
s5:stuff
Run Code Online (Sandbox Code Playgroud)
我可以很容易地看到如何使用PCRE等来解析它,但为了速度,我宁愿坚持使用普通的字符串操作.
我知道我需要分两步完成它,因为在知道它的长度之前我不能分配目标字符串.我的问题是优雅地获得所述字符串开头的偏移量.一些代码:
unsigned start = 0;
char type = serialized[start++]; // get the type tag
int len = 0;
char* dest = NULL;
char format[20];
//...
switch (type) {
//...
case 's':
// Figure out the length of the target string...
sscanf(serialized + start, "%d", &len);
// <code type='graceful'>
// increment start by the STRING LENGTH of whatever %d was
// </code>
// Don't forget to skip over the colon...
++start;
// Build a format string which accounts for length...
sprintf(format, "%%%ds", len);
// Finally, grab the target string...
sscanf(serialized + start, format, string);
break;
//...
}
Run Code Online (Sandbox Code Playgroud)
该代码大致取自我所拥有的(由于手头的问题而不完整),但它应该得到重点.也许我完全采取了错误的做法. 什么是最优雅的方式来做到这一点? 解决方案可以是C或C++(如果有足够的响应,我实际上希望看到竞争方法).
您可以使用%n
转换说明符,它不使用任何输入 - 而是需要一个int *
参数,并将输入中消耗的字符数写入其中:
int consumed;
sscanf(serialized + start, "%d%n", &len, &consumed);
start += consumed;
Run Code Online (Sandbox Code Playgroud)
(但不要忘记检查sscanf()
返回> 0!)