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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!