2017-08-19 26 views
1

我在這裏有一個php問題。我有2個輸入,($ s,$ n),$ s代表一個字符串,$ n代表一個整數。問題是:「將每個字符轉換爲$ s $ n的位置」。php字符增量'Y'和++ 2次

例如$ S = 「AA」,$ N = 2,則輸出爲 「CC」

我有一個小問題就在這裏,如果$ S = 「YY」,$ N = 2時,輸出「aaaa」,但我

希望輸出爲「aa」,我該如何修復我的代碼?下面

是我的代碼:

$words = str_split($s);    

for($i=0;$i<count($words);$i++){ 

    if($words[$i] == " ") { 
    //if space 
    continue; 
    }      
    else{ 
    for($y=0;$y<$n;$y++) 
     $words[$i] = ++$words[$i];     
    }  
} 

$ans = join("", $words); 

print("$ans\n"); 

非常感謝。

+1

如果字符串是什麼,預計'我是Wölf'? – chris85

回答

0

此解決方案可能不是100%正確的。或者可能有更好的解決方案。但我已經嘗試從字符串的子串,如果長度超過了原先的長度

<?php 
$s = "YY"; 
$n = 2; 
$words = str_split($s);    
for($i=0;$i<count($words);$i++){ 

    if($words[$i] == " ") { 
    //if space 
    continue; 
    }      
    else{ 
    for($y=0;$y<$n;$y++){ 
     $cur_len = strlen($words[$i]); 
     $words[$i] = ++$words[$i]; 
     $new_len = strlen($words[$i]); 
     if($new_len > $cur_len) 
     $words[$i] = substr($words[$i], 0,$cur_len);  
    } 
    }  
} 

$ans = join("", $words); 

print("$ans\n"); 
0

之所以你2遞增Ÿ當越來越AA是,它是像一些處理它。因此(例如)9 + 1 = 10,所以進位有一個額外的數字。當你遞增YY的每個數字時,你將得到兩個都帶有AA的元素 - 因此AAAA輸出。

如果你只是想最後一位......

$s = "YY"; 
$n=2; 
$words = str_split($s); 

for($i=0;$i<count($words);$i++){ 
    if($words[$i] != " ") { 
     for($y=0;$y<$n;$y++) { 
      $words[$i]++; 
     } 
     $words[$i]= substr($words[$i],-1); 
    }  
} 

$ans = join("", $words); 

print("$ans\n");