PHP - 大写的Induvidual元素

时间:2015-09-17 09:48:17

标签: php

我正在研究Coderbyte挑战,因为我正在教自己一些PHP。

我一直在努力完成以下挑战(链接如下)

Coderbyte Challenge

我已经得到了以下内容,我有点困惑,因为它现在将数组的每个字母大写,而不是在'if语句'中选择的字母。

我渴望学习,而不仅仅是想要一个没有解释的答案。如果你能告诉我我哪里出错了,以及我是否采取长篇大论的方式做事。

感谢您的帮助。

<?php 

function LetterChanges($str) {  

// code goes here
$str = strtolower($str);
$strArray = str_split($str);

for($i = 0; $i < strlen($str); $i++){

  ++$strArray[$i];

 if($strArray[$i] == "aa"){
   $strArray[$i] = "A";
 }
 elseif($strArray[$i] == "e" || "i" || "o" || "u"){
   $strArray[$i] = strtoupper($strArray[$i]);
 }

 }

 return implode ($strArray); 

 }

 // keep this function call here  
 // to see how to enter arguments in PHP scroll down
 echo LetterChanges(fgets(fopen('php://stdin', 'r')));  

 ?> 

3 个答案:

答案 0 :(得分:2)

您可以使用此代码

function LetterChanges($str){
    $arr = array();
    $strlen = strlen( $str );
    for( $i = 0; $i <= $strlen; $i++ ) {
        $char = substr( $str, $i, 1 );
        ++$char;

        if($char == "a" || $char == "e" || $char== "i" || $char== "o" || $char== "u"){
            $char = strtoupper($char);
        }
        if($char == "aa"){
            $char = 'A';  //When we increase Z it becomes aa so we changed it to A 
        }
        $arr[] = $char;
    }
    //print_r($arr);
    echo implode("",$arr);
}

LetterChanges('hello*3'); 

<强>解释

for循环中,在数组中分别获取每个字符,然后将其增加1然后在增加的字符中检查元音是否存在然后我们将它们更改为大写并再次将该数组更改为简单字符串。

答案 1 :(得分:0)

你不能使用像这样的增加一个角色=&gt; “++ $ strArray [$ I];” 为此你必须首先在php中获得该字符的ascii值,你可以使用ord()函数得到字符的ascii值,然后将ascii值递增1,然后使用chr()函数将其转换回字符。

以下是您问题的完整解决方案:

function LetterChanges($str) {  

// code goes here
$str = strtolower($str);
$strarray = str_split($str);
$newarray = array();
for($i=0; $i<count($strarray); $i++) {
  if(ord($strarray[$i])>=97 && ord($strarray)<=122) {
      $newarray[$i] = chr(ord($strarray[$i])+1);
  } else {
      $newarray[$i] = $strarray[$i];
}
if($newarray[$i]=='a' || $newarray[$i]=='e' || $newarray[$i]=='i' || $newarray[$i]=='o' || $newarray[$i]=='u') {
    $newarray[$i] = strtoupper($newarray[$i]);
}
}

$str = implode('',$newarray);

return $str; 

}

答案 2 :(得分:0)

试试这个..它会起作用

<?php 

 function LetterChanges($str) {  

 $strlen = strlen( $str );

 $out = '';
 for($i = 0; $i <= $strlen; $i++) {
    $char = substr($str,$i,1);
  if(!is_numeric($char)) {
        $nextChar = ++$char;    
        if (strlen($nextChar) > 1) { // if you go beyond z or Z reset to a or A
            $nextChar = $next_ch[0];
        }
    if(in_array($char,array('a','e','i','o','u'))) {
        $nextChar = strtoupper($nextChar);
    }
  }
  else {
    $nextChar = $char;
  }

  $out .= $nextChar;

}
$str = $out;


// code goes here
return $str; 

}

// keep this function call here  
// to see how to enter arguments in PHP scroll down
echo LetterChanges(fgets(fopen('php://stdin', 'r')));  

?>