15 Jun 2024C++ / Python / TypeScriptEasy

Find the Index of the First Occurrence in a String

Collected C++, Python, TypeScript solutions for find the index of the first occurrence in a string. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Find the Index of the First Occurrence in a String. the solution files are available below.

solution files

  • C++ find-the-index-of-the-first-occurrence-in-a-string/synced-solution.cpp
  • Python find-the-index-of-the-first-occurrence-in-a-string/synced-solution.py
  • TypeScript find-the-index-of-the-first-occurrence-in-a-string/synced-solution.ts

Solution files

Pythonfind-the-index-of-the-first-occurrence-in-a-string/synced-solution.py
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)
C++find-the-index-of-the-first-occurrence-in-a-string/synced-solution.cpp
class Solution {
public:
    int strStr(string haystack, string needle) {
        size_t pos = haystack.find(needle);
        return pos == string::npos ? -class="syntax-number">1 : pos;
    }
};
TypeScriptfind-the-index-of-the-first-occurrence-in-a-string/synced-solution.ts
function strStr(haystack: string, needle: string): number {
    return haystack.indexOf(needle);
}