dongyan9950 2017-05-30 18:28
浏览 60
已采纳

请给我一个PHP字符串函数strcmp()的深入分析

Consider the following program:

<?php
      $str1='Hello';
      $str2='hELLo';
      echo strcmp($str1,$str2);
?>

As per my knowledge:

  1. At the point where first mismatch is found the ASCII value difference of the two characters are given.

  2. If the first mismatch is found between a valid character and an empty character the extra number of characters of longer string is given as output.

Hence, the output of above character should be

ASCII value of H - ASCII value of h = 72 - 104 = - 32

My browser gives the same output as well.

However in w3school

the answer is given as -1

Also in phpdotnet

in user contributed notes section, user luizvid at gmail dot come puts forward similar concept as given in w3schools.

Please clear my confusion.

  • 写回答

1条回答 默认 最新

  • dqdl6469 2017-05-30 19:01
    关注

    To wrap this question up:

    The PHP docs generally just state that you can rely on the sign of the result:

    Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

    The effect that it returns the ASCII difference is just that, a side-effect and not guaranteed.

    In fact, as of 2017-05-30:

    • PHP 5.6.0 - 5.6.30 aswell as 7.0.0 - 7.1.5 return the ASCII difference

    while

    • HHVM 3.15.4 - 3.19.0 just returns the sign.

    See Link.

    Long story short: Don't rely on strcmp for anything other than "Are these strings identical or not?".

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类