doulu6234 2015-06-01 12:35
浏览 288
已采纳

使用sscanf读取固定长度的字符串

I'm trying to sscanf to read a bunch of successive fixed length strings but it's not working very well. I can print a fixed length string thusly:

sprintf('%.5s', 'aaaaabbbbb');

But if I try to use %.5s to read a fixed length string (eg. the first 5 bytes of an input string) it doesn't work. eg.

var_dump(sscanf('aaaaabbbbb', '%.5s'));

If I do that var_dump returns NULL and I get the following Warning:

Warning: sscanf(): Bad scan conversion character "."

I tried %5s in addition to %.5s but that doesn't work as desired either. eg.

var_dump(sscanf('aa aabbbbb', '%5s'));

That returns this:

array(1) {
  [0]=>
  string(2) "aa"
}

What I'd want it to return is this:

array(1) {
  [0]=>
  string(5) "aa aa"
}

Any ideas?

  • 写回答

1条回答 默认 最新

  • duanliexi1052 2015-06-01 12:46
    关注

    The problem is that any space character is considered as a new input using %s.

    According to http://php.net/manual/en/function.sscanf.php comment, this should work :

    $result = sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234", 
                 '  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
                 $vendor, $model, $rev);
    

    So, in your case :

    var_dump(sscanf('aa aabbbbb', '%5[ -~]'));
    

    It works fine on PHP 5.2.10.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档