Zenn
🍣

28. Find the Index of the First Occurrence in a String

2025/03/16に公開
2つの文字列 needle と haystack が与えられたとき、haystack の中で needle が最初に現れる位置のインデックスを返してください。もし needle が haystack の一部でない場合は、-1 を返してください。

例 1:

入力: haystack = "sadbutsad", needle = "sad"
出力: 0
説明: "sad" はインデックス 0 と 6 に出現しますが、最初に現れる位置は 0 なので、0 を返します。

例 2:

入力: haystack = "leetcode", needle = "leeto"
出力: -1
説明: "leeto" は "leetcode" 内に存在しないため、-1 を返します。
class Solution {

    /**
     * @param String $haystack
     * @param String $needle
     * @return Integer
     */
    function strStr($haystack, $needle) {
        
        $position = strpos($haystack, $needle);

        return $position !== false ? $position: -1;
    }
}

Discussion

ログインするとコメントできます