Implement strStr() (Substring Search)

beginner
24 min

Implement strStr() (Substring Search)

Welcome to our detailed guide on the strStr() function, a key concept in the world of data structures and algorithms! This tutorial is designed to help both beginners and intermediate learners understand this essential function, and we'll do so in a way that's engaging, practical, and easy to follow. Let's dive right in!

What is strStr()? šŸŽÆ

The strStr() function is used in many programming languages to find the position of a substring within a given string. This function is useful when you want to locate specific pieces of data in a larger data set.

Why do we need strStr()? šŸ’”

Imagine you have a large text file and want to find all instances of a particular word. Without the strStr() function, this would be a time-consuming and error-prone process. By using strStr(), you can quickly and accurately find the positions of your desired substring, making your code more efficient and reliable.

Understanding the Function šŸ“

Here's the basic syntax for the strStr() function:

int strStr(char *haystack, char *needle);
  • haystack: The string in which you're searching for the substring.
  • needle: The substring you're looking for.

Implementing strStr() āœ…

Now, let's write a simple implementation of the strStr() function in C:

c
#include <stdio.h> #include <string.h> int strStr(char *haystack, char *needle) { int i, j, haystackLen, needleLen; haystackLen = strlen(haystack); needleLen = strlen(needle); // Loop through the haystack for (i = 0; i <= haystackLen - needleLen; i++) { // Check if the substring matches for (j = 0; j < needleLen; j++) { if (haystack[i + j] != needle[j]) break; } // If the loop completed without breaking, we found a match if (j == needleLen) return i; } // If no match was found, return -1 return -1; } int main() { char haystack[] = "Hello, World!"; char needle[] = "World"; int result = strStr(haystack, needle); if (result != -1) printf("Substring found at position %d\n", result); else printf("Substring not found\n"); return 0; }

In this example, we're searching for the substring "World" in the string "Hello, World!". The strStr() function will return the position of the substring within the larger string, which is 6 in this case.

Quiz Time! šŸŽ²

Quick Quiz
Question 1 of 1

What does the `strStr()` function return when it can't find the substring in the given string?

By now, you should have a good understanding of the strStr() function and its importance in programming. Keep practicing, and happy coding! šŸš€