【问题标题】:how to store last character of the world from the string into an array in PHP如何将字符串中的最后一个字符存储到PHP中的数组中
【发布时间】:2016-05-03 12:54:24
【问题描述】:

我有一个类似 -

的字符串
$str = "Hello how are you";

我想将最后一个字符存储在数组中,结果如下所示-

array(0=>o,1=>w,2=>e,3=>u)

如何不使用php的explode()substr()array_split()方法来实现。

【问题讨论】:

  • "没有使用php重新定义函数" 为什么?这就像在问:“我如何在没有 PHP 代码的情况下用 PHP 编写代码”。
  • 你可以自己写。 ://
  • 其实这个问题是在面试中问到我的
  • predefined 表示php内置函数,如explode()、array_split()等
  • 那么什么是允许的?是否允许使用循环和访问数组元素?还有什么在这里定义为单词分隔符?

标签: php arrays string


【解决方案1】:

这无需任何函数调用即可工作(isset 实际上是一种语言结构,而不是函数。) :

$str = "Hello how are you";

for ($i = 0; isset($str[$i]); $i++) {
    if (!isset($str[$i + 1]) || $str[$i + 1] == " ") {
        $result[] = $str[$i];
    }
}

它一次寻址一个字符串的每个字节,检查它是否是最后一个字节或后跟一个空格,如果是,则将其添加到数组中。这是一组用于确定单词结尾的简单规则,但说明了这个想法。

使用print_r($result) 输出验证:

Array
(
    [0] => o
    [1] => w
    [2] => e
    [3] => u
)

【讨论】:

    【解决方案2】:

    我不知道为什么要这样做,但我明白了

    $str = "Hello how are you";
    $last='';
    $i=0;
    $result=array();
    
    while ($i<strlen($str)){
    if ($str[$i]==' '){
    $result[]=$last;    
    }
    $last= $str[$i];
    if ($i==(strlen($str)-1)){
    $result[]=$last;        
    }
    $i++;
    }
    print_r($result);
    

    【讨论】:

      【解决方案3】:

      使用str_word_count函数的替代方案:

      $str = "Hello how are you";
      $last_chars = [];
      foreach (str_word_count($str, 1) as $word) {
          $last_chars[] = $word[strlen($word) - 1];
      }
      
      print_r($last_chars);
      

      输出:

      Array
      (
          [0] => o
          [1] => w
          [2] => e
          [3] => u
      )
      

      【讨论】:

        【解决方案4】:

        正如您提到的,您不想使用explodesubstrsplit,所以现在您需要使用strlen 来获取字符串长度。

        得到数组长度后,你需要遍历长度并检查字符是blank space还是last character。如果然后将前一个字符添加到输出数组中。

        $str = "Hello how are you";
        
        $length = strlen($str);
        $out = array();
        for($i = 0; $i < $length; $i++){
            if($str[$i] == " " || ($i == $length - 1)){
                $out[] = $str[$i-1];
            }
        }
        
        print_r($out);
        

        结果

        Array
        (
            [0] => o
            [1] => w
            [2] => e
            [3] => u
        )
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,这会降低代码和解释的可读性!
        • 另外你自己编辑了这个问题,所以你可能已经读过:without php explode(), substr()的使用
        • @Rizier123,现在我使用了其他一些函数。
        猜你喜欢
        • 1970-01-01
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-03
        • 1970-01-01
        • 2017-09-27
        相关资源
        最近更新 更多