我想編寫一個函數,它可以使用strlen + substr + strpos來計算子字符串在字符串中出現的次數,在PHP中。使用strlen + substr + strpos只計算一個字符串中出現子字符串的次數PHP
沒有使用substr_count
!
例如:fn('iwritecodeiwritecode-','i');
感謝提前
我想編寫一個函數,它可以使用strlen + substr + strpos來計算子字符串在字符串中出現的次數,在PHP中。使用strlen + substr + strpos只計算一個字符串中出現子字符串的次數PHP
沒有使用substr_count
!
例如:fn('iwritecodeiwritecode-','i');
感謝提前
function fn($string, $char){
$count=0;
for($i=0; $i<strlen($string);$i++){
if($string[$i] == $char){
$count++;
}
}
print($count);
}
fn('iwritecodeiwritecode-','i');
我希望它有助於乾杯!
我想出了我自己的最佳解決方案。
<?php
$str = "iwritecodeiwritecode";
function find_substr_count($str, $substr) {
$substr_len = strlen($substr);
$substr_count = 0;
for($i = 0; $i < strlen($str); $i++) {
$substr_temp = '';
for($j = $i; $j < $i + $substr_len; $j++) {
if($j < strlen($str)) {
$substr_temp .= $str[$j];
}
}
if($substr_temp == $substr) {
$substr_count += 1;
}
}
return $substr_count;
}
echo find_substr_count($str, "i");
?>
它不僅適用於單個字符。您也可以嘗試通過兩個或多個字符的功能,如:
echo find_substr_count($str, "write");
我已經給了我所能來幫助你。
希望它有幫助!
對於此任務,您不需要strlen()
或substr()
。
只用一個while循環迭代你的字符串,每找到一個成功的針就提前輸出strpos()
並計算成功匹配的次數。
該技術中的「魔術」使用前面的strpos()
值(加1)作爲所有後續調用的起始點。
代碼:(Demo)
function countSubstrings($haystack,$needle){
$pos=-1; // start at -1 so that first iteration uses $pos of 0 as starting offset
$tally=0;
while(($pos=strpos($haystack,$needle,++$pos))!==false){++$tally;}
return $tally;
}
echo countSubstrings('iwritecodeiwritecodeiwritecode','i'); // 6
echo countSubstrings('iwritecodeiwritecodeiwritecode','Perumal'); // 0
echo countSubstrings('iwritecodeiwritecodeiwritecode','write'); // 3
的注意事項,以未來的讀者,這個問題是不是最好的做法。正確的方法是簡單調用已有的php函數
substr_count()
。echo substr_count('iwritecodeiwritecodeiwritecode','i');
不要老師拿出作業 – RiggsFolly
的一些narly位,但因爲你有沒有嘗試任何事情,我們不能幫助,因爲SO是不要讓你的功課,爲你做一個地方。如果你嘗試了某些東西並遇到問題,那麼可以詢問關於你遇到的具體問題的具體問題。我們非常樂意幫助一個測試者 – RiggsFolly
PHP字符串也可以當作數組來對待。 –