Find The Index Of First Occurence in a String

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 78 :- Find The Index Of First Occurence in a String

To find the index of the first occurrence of a substring in a string, you can use string searching algorithms like the simple brute-force method or more efficient algorithms like the Knuth-Morris-Pratt (KMP) algorithm or the Boyer-Moore algorithm. Here, I'll show you how to implement the brute-force method in Python:

pythonCopy code

def find_first_occurrence(text, pattern):    n = len(text)    m = len(pattern)    for i in range(n - m + 1):        j = 0        while j < m and text[i + j] == pattern[j]:            j += 1        if j == m:            return i    return -1 # Example usage: text = "hello world" pattern = "world" index = find_first_occurrence(text, pattern) print(index)

Output:

Copy code

6

In this example, the function find_first_occurrence takes two arguments, text (the input string) and pattern (the substring we want to find). The function iterates through the text using a sliding window of length equal to the length of the pattern. It compares the characters in the window with the characters of the pattern.

If it finds a match, it returns the starting index of the first occurrence of the pattern in the text. If there's no match, it returns -1 to indicate that the pattern is not present in the text.

Keep in mind that the brute-force method has a time complexity of O(n * m), where n is the length of the text and m is the length of the pattern. For larger texts and patterns, more efficient algorithms like KMP or Boyer-Moore should be used to improve performance.

11. Week5 - Assignments

Comments: 2

profile
@mk.info.work
17-Feb-2024, 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

profile
@na3744
23-Feb-2024, 02:52 AM

I bought this course, it worth it!

profile
@mk.info.work
15-Nov-2023, 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

profile
@sciaku1
11-Jan-2024, 03:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?