【问题标题】:String mutation in array elements数组元素中的字符串突变
【发布时间】:2017-04-19 02:01:18
【问题描述】:

我想操作数组元素。因此,如果某个数组元素以字母nm 结尾,并且以下元素是例如apple,那么我想删除“apple”的“a”,以便得到输出:@987654324 @

我的代码:

$input = array("man","apple");

$ending = array("m","n");

$example = array("apple","orange");


for($i=0;$i<count($input);$i++)
{
   $second = isset( $input[$i+1])?$input[$i+1][0]:null;


   $third = substr($input[$i],-2);




        if( isset($third) && isset($second) ){
                    if (   in_array($third,$ending) && in_array($second,$example) ){
                    $input[$i+1] = substr($input[$i+1],0,-2);
                    }

        }   



}  

如何更改我的代码以获得所需的输出?

【问题讨论】:

  • 那么如果数组是这样的输出会是什么:array("man", "ham", "apple");,会是array("man", "am", "pple");吗?
  • @RajdeepPaul 不,它与输出相同
  • 那么这背后的逻辑是什么? mann 结尾,因此ham 的开头字母h 被删除。同样,现在am 以字母m 结尾,因此apple 的字母a 被删除,保留为pple,不是吗?请澄清问题中的逻辑。
  • @RajdeepPaul 仅当一个单词的结尾字母是 n 并且下一个单词是 appleorange 时,这两个单词的第一个字母会被删除。逻辑并不重要……只是一个简单的案例来理解它……
  • @MoeJoe 你可以查看我的任务解决方案。

标签: php arrays string-matching


【解决方案1】:

听起来像是一项很酷的锻炼任务。

阅读开始的 cmets 后,我的处理方法是这样的:

$input = ['man', 'hamster', 'apple', 'ham', 'red'];
$endings = ['m', 'n'];

$shouldRemove = false;
foreach ($input as $key => $word) {
    // if this variable is true, it will remove the first character of the current word.
    if ($shouldRemove === true) {
        $input[$key] = substr($word, 1);
    }

    // we reset the flag 
    $shouldRemove = false;
    // getting the last character from current word
    $lastCharacterForCurrentWord = $word[strlen($word) - 1];

    if (in_array($lastCharacterForCurrentWord, $endings)) {
        // if the last character of the word is one of the flagged characters,
        // we set the flag to true, so that in the next word, we will remove 
        // the first character.
        $shouldRemove = true;
    }
}

var_dump($input);
die();

这个脚本的输出是

array(5) { [0]=&gt; string(3) "man" [1]=&gt; string(6) "amster" [2]=&gt; string(5) "apple" [3]=&gt; string(3) "ham" [4]=&gt; string(2) "ed" }

我希望与 cmets 的解释就足够了。

【讨论】:

  • 并不总是如果单词以某个字母结尾,则下一个第一个字母将被删除。仅当下一个单词是appleorange
猜你喜欢
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多