ZeroToSky
C Programming Tutorial 94 of 206
Introduction & Setup
  • Introduction to C
  • History of C
  • Features of C
  • Applications of C
  • Advantages and Limitations of C
  • C Standards and Implementations
  • How C Programs Run
  • Setting Up C Development Environment
  • Your First C Program
  • Basic Syntax of C
  • Structure of a C Program
  • Compilation Process in C

All 12 lessons →

Tokens & Basics
  • Tokens in C
  • Keywords in C
  • Identifiers in C
  • Constants in C
  • Variables in C
  • Scope Rules in C
  • Storage Classes in C
  • Comments in C

All 8 lessons →

Data Types & I/O
  • Data Types in C
  • Primitive Data Types
  • Derived Data Types
  • Type Modifiers
  • Type Conversion in C
  • Type Casting in C
  • sizeof Operator
  • Input and Output in C
  • printf() in C
  • scanf() in C
  • Character I/O: getchar and putchar
  • String I/O: gets/fgets and puts
  • Format Specifiers in C

All 13 lessons →

Operators & Expressions
  • Operators in C
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Increment and Decrement Operators
  • Conditional Operator
  • Comma Operator
  • sizeof and Address Operators
  • Operator Precedence and Associativity
  • Expression Evaluation in C
  • Short-Circuit Evaluation

All 13 lessons →

Control Flow
  • Decision Making in C
  • if Statement
  • if-else Statement
  • else-if Ladder
  • Nested if
  • switch Statement
  • Loops in C
  • for Loop
  • while Loop
  • do-while Loop
  • Nested Loops
  • break Statement
  • continue Statement
  • goto Statement

All 14 lessons →

Functions
  • Functions in C
  • Function Declaration and Definition
  • Function Arguments
  • Return Values
  • Call by Value
  • Call by Reference Using Pointers
  • Parameter Passing Techniques
  • Main Function in C
  • Recursion in C
  • Types of Recursion
  • Inline Functions
  • Nested Functions
  • Function Pointers
  • Variadic Functions

All 14 lessons →

Arrays
  • Arrays in C
  • Declaration and Initialization of Arrays
  • Accessing Array Elements
  • Traversing an Array
  • Passing Arrays to Functions
  • Array Parameters and Pointers
  • One-Dimensional Arrays in C
  • Two Dimensional Arrays
  • Multidimensional Arrays in C
  • Passing 2D Arrays to Functions
  • Array of Pointers
  • Variable Length Arrays

All 12 lessons →

Strings
  • Strings in C
  • String Declaration and Initialization
  • String Length
  • String Traversal
  • String Comparison
  • String Copy
  • String Concatenation
  • Substring Search
  • String Tokenization
  • String Reverse
  • Palindrome String in C
  • String Pattern Searching
  • String Literals

All 13 lessons →

Pointers
  • Pointers in C
  • Address and Dereference Operators
  • Pointer Arithmetic
  • Pointers and Arrays
  • Pointer to Pointer
  • Void Pointers
  • Null Pointers
  • Dangling Pointers
  • Wild Pointers
  • Constant Pointers and Pointer to Constant
  • Function Pointers
  • Array of Pointers
  • Pointers to Functions
  • Pointers to Structures
  • Pointer Type Casting

All 15 lessons →

Structures & Unions
  • Structures in C
  • Structure Members
  • Array of Structures
  • Nested Structures
  • Pointers to Structures
  • Passing Structures to Functions
  • Structure Alignment and Padding
  • Self-Referential Structures
  • Bit Fields in Structures
  • Unions in C
  • Structure vs Union
  • Enumeration in C
  • typedef in C

All 13 lessons →

Dynamic Memory & Memory
  • Program Memory Layout in C
  • Stack and Heap in C
  • malloc()
  • calloc()
  • realloc()
  • free()
  • Dynamic Arrays
  • Memory Leaks
  • Dangling Memory
  • Double Free
  • Use After Free
  • Memory Safety Best Practices

All 12 lessons →

Preprocessor & Headers
  • C Preprocessor
  • Header Files in C
  • #include Directive
  • #define and Macros
  • Function-like Macros
  • Conditional Compilation
  • #ifdef, #ifndef and #endif
  • Predefined Macros
  • Pragma Directive
  • Include Guards

All 10 lessons →

File Handling
  • File Handling in C
  • File Pointers
  • fopen() and fclose()
  • Reading a File
  • Writing to a File
  • Appending to a File
  • fgetc() and fputc()
  • fgets() and fputs()
  • fprintf() and fscanf()
  • Binary File Handling
  • EOF, getc() and feof()
  • Read/Write Structures to Files
  • Delete a File
  • File Error Handling

All 14 lessons →

Error Handling & Debugging
  • Error Handling in C
  • perror()
  • strerror()
  • errno
  • Assertions in C
  • Debugging C Programs
  • Common C Runtime Errors
  • Divide by Zero Handling
  • goto for Error Handling

All 9 lessons →

Date, Time & Misc
  • Date and Time in C
  • time() Function
  • clock() Function
  • Random Numbers in C
  • Linkage in C
  • External and Static Linkage
  • Storage Duration
  • Integer Overflow and Undefined Behavior
  • Implementation-Defined vs Undefined Behavior

All 9 lessons →

Advanced C
  • Generic Selection (_Generic)
  • Variadic Functions
  • Input/Output System Calls
  • Signals in C
  • Signal Handling
  • Socket Programming in C
  • Multithreading in C
  • Threads and Synchronization
  • Atomic Operations
  • Memory-Mapped Files
  • Low-Level Systems Programming

All 11 lessons →

Practice & Projects
  • C Programming Examples
  • C Exercises
  • C Fundamental Practice Problems
  • C Functions Practice Problems
  • C Compound Data Type Practice Problems
  • C Pattern Programs
  • C Array Programs
  • C String Programs
  • C Pointer Programs
  • C Structure and Union Programs
  • C File Handling Projects
  • C Mini Projects
  • C Interview Questions
  • Data Structures and Algorithms in C

All 14 lessons →

Substring Search

Learn how to search for a substring inside a string in C using character comparison, traversal, and built-in string functions.

Gaurav 3 min read Sign in to save
On this page

Substring Search in C

Substring search is the process of finding whether a smaller string (substring) exists inside a larger string.

For example:

Text:      "programming"
Substring: "gram"

The substring "gram" exists inside "programming".

Substring searching is commonly used in string processing, pattern matching, text searching, and DSA problems.


Basic Idea

To search for a substring, compare the characters of the substring with characters in the main string.

For example:

Text:      "hello world"
Pattern:       "world"

The search starts at different positions in the text until all characters of the pattern match.


Using strstr()

C provides the strstr() function in the <string.h> header for substring searching.

Syntax

strstr(string, substring);

It returns a pointer to the first occurrence of the substring.

Example

#include <stdio.h>
#include <string.h>

int main() {
    char text[] = "Hello World";
    char pattern[] = "World";

    char *result = strstr(text, pattern);

    if (result != NULL)
        printf("Substring found");
    else
        printf("Substring not found");

    return 0;
}

Output:

Substring found

Searching Manually

Understanding the manual approach is important for DSA because many string-searching problems require you to implement the logic yourself.

#include <stdio.h>
#include <string.h>

int main() {
    char text[] = "programming";
    char pattern[] = "gram";

    int n = strlen(text);
    int m = strlen(pattern);
    int found = 0;

    for (int i = 0; i <= n - m; i++) {
        int j;

        for (j = 0; j < m; j++) {
            if (text[i + j] != pattern[j])
                break;
        }

        if (j == m) {
            found = 1;
            break;
        }
    }

    if (found)
        printf("Substring found");
    else
        printf("Substring not found");

    return 0;
}

The outer loop selects a possible starting position, while the inner loop compares the pattern characters.


Example

Consider:

Text:    "abcdef"
Pattern: "cde"

The comparisons are:

abcdef
cde

abcdef
 cde

abcdef
  cde

At the third position:

c == c
d == d
e == e

Therefore, the substring is found.


Finding the Starting Position

Instead of only checking whether a substring exists, we can return its starting index.

int findSubstring(char text[], char pattern[]) {
    int n = strlen(text);
    int m = strlen(pattern);

    for (int i = 0; i <= n - m; i++) {
        int j;

        for (j = 0; j < m; j++) {
            if (text[i + j] != pattern[j])
                break;
        }

        if (j == m)
            return i;
    }

    return -1;
}

Example:

int index = findSubstring("programming", "gram");

The result is:

3

because "gram" starts at index 3.


Time Complexity

For the basic brute-force approach:

  • Worst-case time: O(n × m)
  • Space: O(1)

Where:

  • n = length of the text
  • m = length of the pattern

More advanced algorithms such as KMP can improve substring searching to O(n + m).


Common Mistakes

1. Searching beyond the valid starting position

The outer loop should normally run while:

i <= n - m

because the pattern must have enough remaining characters to match.

2. Forgetting the null character

C strings end with:

'\0'

Functions such as strlen() and strstr() work with null-terminated strings.

3. Confusing substring with subsequence

A substring contains consecutive characters.

"abc" → substring of "abcdef"

But:

"ace"

is not a substring of "abcdef" because the characters are not consecutive.


Approach Use
strstr() Convenient library-based search
Manual search Useful for learning and DSA problems
KMP Efficient pattern matching
Other pattern algorithms Useful for advanced string searching

Quick Reference

#include <string.h>

char *result = strstr(text, pattern);

Manual search:

for (int i = 0; i <= n - m; i++) {
    int j;

    for (j = 0; j < m; j++) {
        if (text[i + j] != pattern[j])
            break;
    }

    if (j == m) {
        // Pattern found
    }
}

Key Takeaways

  • Substring search finds a smaller string inside a larger string.
  • strstr() is the standard C library function for substring searching.
  • Manual substring search uses nested loops to compare characters.
  • The brute-force approach has O(n × m) worst-case time complexity.
  • Substring characters must occur consecutively.
  • Efficient algorithms such as KMP can reduce searching to O(n + m).

Practice Questions

  1. Write a C program to check whether a substring exists in a string.
  2. Find the first occurrence of a substring without using strstr().
  3. Count how many times a substring occurs in a string.
  4. Find the starting index of every occurrence of a substring.
  5. Implement substring search using the brute-force approach.

What's Next?

Next, explore String Pattern Matching to understand how algorithms efficiently search for patterns in larger strings.

Related

Found a problem on this page, or something that could be clearer?

Goes straight to the author. Not published anywhere.