Bird
0
0
DSA Cprogramming~30 mins

String Pattern Matching Naive in DSA C - Build from Scratch

Choose your learning style9 modes available
String Pattern Matching Naive
📖 Scenario: You are building a simple text search tool that looks for a small pattern inside a larger text. This is like finding a word in a book by checking each letter one by one.
🎯 Goal: Build a program that uses the naive method to find all positions where a given pattern appears in a text string.
📋 What You'll Learn
Create a character array text with the exact value "abracadabra"
Create a character array pattern with the exact value "abra"
Create an integer variable text_length that stores the length of text
Create an integer variable pattern_length that stores the length of pattern
Use a nested for loop with variables i and j to check for pattern matches in text
Print all starting indices where pattern is found in text separated by spaces
💡 Why This Matters
🌍 Real World
Searching for keywords in documents, logs, or DNA sequences using simple matching.
💼 Career
Understanding basic string search algorithms is essential for roles in software development, data processing, and bioinformatics.
Progress0 / 4 steps
1
Create the text and pattern strings
Create a character array called text with the exact value "abracadabra" and a character array called pattern with the exact value "abra".
DSA C
Hint

Use double quotes to create string arrays in C.

2
Calculate lengths of text and pattern
Create an integer variable called text_length that stores the length of text using sizeof(text) - 1. Create an integer variable called pattern_length that stores the length of pattern using sizeof(pattern) - 1.
DSA C
Hint

Use sizeof to get the size of the array including the null character, so subtract 1.

3
Implement the naive pattern matching logic
Use a for loop with variable i from 0 to text_length - pattern_length. Inside it, use another for loop with variable j from 0 to pattern_length to check if pattern[j] matches text[i + j]. If all characters match, print the index i followed by a space.
DSA C
Hint

Use nested loops to compare each character of the pattern with the text starting at index i.

4
Print a newline after all matches
Add a printf statement to print a newline character \n after printing all matching indices.
DSA C
Hint

Use printf("\n") to move to the next line after printing all matches.