如何獲取字符串1中沒有php內置函數的字符串2發生次數。如何獲取字符串1中沒有php內置函數的字符串2的發生次數
例子:
$strone = "Arun sukumar";
$strtwo = "a";
//Expected Output: 2
$strone = "Arun sukumar";
$strtwo = "uk";
//Expected Output: 1
我需要獲得計數,而使用內置功能的任何PHP。
這是面試中問的問題,有沒有什麼邏輯呢?
如何獲取字符串1中沒有php內置函數的字符串2發生次數。如何獲取字符串1中沒有php內置函數的字符串2的發生次數
例子:
$strone = "Arun sukumar";
$strtwo = "a";
//Expected Output: 2
$strone = "Arun sukumar";
$strtwo = "uk";
//Expected Output: 1
我需要獲得計數,而使用內置功能的任何PHP。
這是面試中問的問題,有沒有什麼邏輯呢?
$strone = 'arun sukumar';
$strtwo = 'a';
echo parsestr($strone, $strtwo);
function parsestr($strone, $strtwo)
{
$len = 0;
while ($strtwo{$len} != '') {
$len++;
}
$nr = 0;
while ($strone{$nr} != '')
{
if($strone{$nr} != ' ')
{
$data[$nr] = $strone{$nr};
}
$nr++;
}
$newdata = $data;
if($len > 1)
{
$newdata = array();
$j = 0;
foreach($data as $val)
{
$str .= $val;
if($j == ($len -1))
{
$newdata[] = $str;
$str = '';
$j = 0;
}
else
$j++;
}
}
$i = 0;
foreach($newdata as $val)
{
if($val == $strtwo)
{
$i++;
}
}
return $i;
}
不知道爲什麼你會不希望使用內置的PHP功能,因爲它們會更快,但像這樣的工作:
<?php
$haystack = 'Arun sukumar';
$needle = 'a';
// you seem to want a case insensitive search, so do a strtolower first
$haystack = strtolower($haystack);
$hitCount = 0;
for ($i = 0; $i < strlen($haystack); ++$i) {
if ($needle === substr($haystack, $i, strlen($needle))) {
$hitCount++;
}
}
echo 'Output: ' . $hitCount;
?>
umm strlen,strtolower,substr arent內置函數????? – prodigitalson
我不認爲這符合OP ... – Ben
的要求,您在這裏使用4個內置函數... – evilone
你需要把你的針,得到的第一個字符然後遍歷乾草堆的每個字符,直到你匹配。然後拿下下一個字符的針,檢查乾草堆的下一個字符是否匹配...繼續,直到你完全匹配針頭或直到你匹配字符。
提示:您可以通過索引$string{0}
來訪問字符串的各個字符,其中0
是字符串中char的從零開始的索引。
你能否以上述問題 –
的例子爲例簡述'$ string {0}'已被棄用,你應該使用'$ string [0]' –
試試這個
$string = 'Arun sukumar';
$sub_string = 'a';
$count = 0;
for($i=0;$i < strlen($string); $i++){
$flag = 0;
$j=0;
if(strtolower($string[$i]) == $sub_string[$j])
{
//echo "match";
$flag = 1;
$k = $i;
for(;$j< strlen($sub_string); $j++){//echo "[".$j . $k."] $count $flag";
if(strtolower($string[$k]) != $sub_string[$j]){
$flag = 0;
break;
}
$k++;
}//echo "<br> $flag";
}
if($flag == 1){
$count++;
$flag = 0;
}
}
echo $count;
?>
雖然這段代碼是受歡迎的,並且可以提供一些幫助,如果它包含* how *和* why *解釋問題的解釋](// meta.stackexchange.com/q/114762),[會大大改進]。請記住,你正在爲將來的讀者回答這個問題,而不僅僅是現在問的人!請編輯您的答案以添加解釋,並指出適用的限制和假設。 –
謝謝@TobySpeight。我是新的stackoverflow。我想知道關於解釋,我應該在代碼中添加註釋嗎? –
最好寫一個介紹性的描述,並且只爲自己編寫代碼時註釋代碼。看起來你的答案顯示瞭如何迭代字符串,在每個索引處執行比較,以便可以作爲解釋的開始。如果我錯了,那麼描述我的錯誤將是完美的! –
功課的問題嗎? – prodigitalson
循環通過字符想到... – evilone
不想使用內置的PHP函數?不要使用PHP。 – trutheality