Find the Index of the First Occurrence in a String

🏠 ⬅️ ➡️

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "sadbutsad ", needle = "sad " Output: 0 Explanation: "sad " occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = "leetcode ", needle = "leeto " Output: -1 Explanation: "leeto " did not occur in "leetcode ", so we return -1.

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    integer :: i, j, k
    character(len=10) :: needle, haystack

    ! Example 1
    needle = 'sad '
    haystack = 'sadbutsad '
    i = str_index(haystack, needle)
    write (*,*) 'Example 1:'
    write (*,'(A,I0)') 'Index of first occurrence of "', needle, '" in "', haystack, '" is ', i

    ! Example 2
    needle = 'leeto '
    haystack = 'leetcode '
    i = str_index(haystack, needle)
    write (*,*) 'Example 2:'
    write (*,'(A,I0)') 'Index of first occurrence of "', needle, '" in "', haystack, '" is ', i

contains

    function str_index(haystack, needle) result(i)
        implicit none
        character(*), intent(in) :: haystack, needle
        integer :: i

        do i = 1, len(haystack)-len(needle)+1
            if (haystack(i:i+len(needle)-1) == needle) then
                exit
            end if
        end do

        if (i > len(haystack)-len(needle)+1) then
            i = -1
        end if
    end function str_index

end program main
Compiled
Executed
Correct
program first_occurrence
      implicit none

      integer :: i, j, k, l
      character(len=100) :: haystack, needle

      read(*,*) haystack
      read(*,*) needle

      l = len(haystack)
      k = len(needle)

      do i = 1, l-k+1
        do j = 1, k
          if (haystack(i+j-1:i+j-1) /= needle(j:j)) exit
        end do
        if (j > k) then
          write(*,*) i
          exit
        end if
      end do

      if (i > l-k+1) then
        write(*,*) -1
      end if

      end program first_occurrence

This program uses a nested loop to iterate over the characters of the `haystack` and `needle` strings. The outer loop iterates over the characters of the `haystack`, while the inner loop iterates over the characters of the `needle`. The program checks if the current character of the `haystack` is equal to the current character of the `needle`. If the characters are not equal, the inner loop exits and the outer loop continues with the next character of the `haystack`. If the characters are equal, the inner loop continues until it reaches the end of the `needle`. If the inner loop reaches the end of the `needle`, the program outputs the index of the first occurrence of the `needle` in the `haystack`. If the `needle` is not part of the `haystack`, the program outputs `-1`.

The program uses the `len` function to get the length of the `haystack` and `needle` strings. The `len` function returns the number of characters in the string. The program uses this value to determine the maximum index of the `haystack` and `needle` strings.

The program uses the `write` statement to output the result to the console. The `write` statement takes two arguments: the first argument is the unit number (in this case, `*`) and the second argument is the value to be written to the console. The program uses the `*` unit number to indicate that the output should be written to the console. The program uses the `write` statement to output the index of the first occurrence of the `needle` in the `haystack` or `-1` if the `needle` is not part of the `haystack`.

The program uses the `exit` statement to exit the inner loop if the characters of the `needle` are not found in the `haystack`. The `exit` statement takes one argument: the label of the loop to exit. In this case, the label of the loop to exit is `j`. The program uses the `exit` statement to exit the inner loop if the characters of the `needle` are not found in the `haystack`.

The program uses the `if` statement to check if the `needle` is not part of the `haystack`. If the `needle` is not part of the `haystack`, the program outputs `-1`. The `if` statement takes two arguments: the condition to be checked and the statement to be executed if the condition is true. In this case, the condition is `i > l-k+1`, which checks if the index of the first occurrence of the `needle` in the `haystack` is greater than the maximum index of the `haystack` minus the length of the `needle` plus one. If the condition is true, the program outputs `-1`.

The program uses the `end program` statement to indicate the end of the program. The `end program` statement is required at the end of every Fortran program.

This program solves the problem by finding the first occurrence of the `needle` in the `haystack`. If the `needle` is not part of the `haystack`, the program outputs `-1`. The program uses a nested loop to iterate over the characters of the `haystack` and `needle` strings. The program checks if the current character of the `haystack` is equal to the current character of the `needle`. If the characters are not equal, the inner loop exits and the outer loop continues with the next character of the `haystack`. If the characters are equal, the inner loop continues until it reaches the end of the `needle`. If the inner loop reaches the end of the `needle`, the program outputs
🌐 Data from online sources
def strStr(haystack: str, needle: str) -> int:
    if not needle:
        return 0
    try:
        index = haystack.index(needle)
        return index
    except ValueError:
        return -1

The algorithm searches for the first occurrence of the needle string in the haystack string. First, it checks if the needle is empty, and if it is, it returns 0. Otherwise, it uses the built-in find, indexOf or index functions provided by the corresponding language's string data type. These functions return the index of the first occurrence of the specified substring. If the substring is not found, they return specific values like string::npos for C++, -1 for Java, and raise a ValueError exception for Python. Depending on the returned value, the algorithm either returns the index of the first occurrence or -1, indicating that needle is not part of haystack.

🌐 Data from online sources
int strStr(string haystack, string needle) {
    if(needle.empty()) return 0;

    size_t pos = haystack.find(needle);
    if(pos != string::npos)
        return pos;
    return -1;
}

The algorithm searches for the first occurrence of the needle string in the haystack string. First, it checks if the needle is empty, and if it is, it returns 0. Otherwise, it uses the built-in find, indexOf or index functions provided by the corresponding language's string data type. These functions return the index of the first occurrence of the specified substring. If the substring is not found, they return specific values like string::npos for C++, -1 for Java, and raise a ValueError exception for Python. Depending on the returned value, the algorithm either returns the index of the first occurrence or -1, indicating that needle is not part of haystack.