【发布时间】:2010-12-09 03:49:14
【问题描述】:
我正在解析一个遵循可预测模式的字符串:
- 1 个字符
- 一个整数(一位或多位数字)
- 1 个冒号
- 一个字符串,其长度来自#2
例如:
s5:stuff
我可以很容易地看到如何使用 PCRE 或类似方法来解析它,但为了速度,我宁愿坚持使用纯字符串操作。
我知道我需要分两步完成,因为在我知道它的长度之前我无法分配目标字符串。我的问题是优雅地获取所述字符串的 start 的偏移量。一些代码:
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;
//...
}
该代码大致取自我所拥有的(由于手头的问题,该代码不完整),但它应该能说明问题。也许我完全采取了错误的方法。 什么是最优雅的方法?解决方案可以是 C 或 C++(如果有足够的响应,我实际上希望看到竞争方法)。
【问题讨论】:
标签: c++ c string parsing scanf