Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
How to Reverse a String in C?
Next article icon

How to Match a Pattern in a String in C?

Last Updated : 15 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Matching a pattern in a string involves searching for a specific sequence of characters within a larger string. In this article, we will learn different methods to efficiently match patterns in a string in C.

The most straightforward method to match a string is by using strstr() function. Let’s take a look at an example:

C
#include <stdio.h> #include <string.h>  int main() {     char s[] = "hello geeks";     char p[] = "geeks";      // Using strstr to find first occurrence     // of the pattern p in s     char *res = strstr(s, p);      if (res != NULL)         printf("Found at position: %ld", res - s);     else         printf("Not found.");      return 0; } 

Output
Found at position: 6

Explanation: The strstr() function in C is used to find the first occurrence of a substring (pattern) within a larger string. It returns a pointer to the first occurrence of the pattern in the string, or NULL if the pattern is not found. The function performs a case-sensitive search, meaning it will only match the exact characters as specified in the pattern.

There are also a few other methods to match a pattern in a string in C. Some of them are as follows:

Using Regular Expressions

We can use the regcomp() function to compile a regular expression pattern and regexec() to search for it in the given string. If the pattern matches the string, the function returns 1, otherwise, it returns 0.

C
#include <stdio.h> #include <string.h> #include <regex.h>  int search(char *s, char *p) {     regex_t regex;     int ret;      // Compile the regular expression     ret = regcomp(&regex, p, 0);      // Execute the regular expression match     ret = regexec(&regex, s, 0, NULL, 0);     regfree(&regex);      // Return 1 if match found, 0 otherwise     return ret == 0;   }  int main() {     char s[] = "hello geeks";     char p[] = "geeks";      	// Matching pattern p in string s     int res = search(s, p);     if (res)         printf("Found");     else         printf("Not found.");      return 0; } 

Output
Found

Using a Loop

In this method, we iterate through the string and compare each character in the string with the pattern. If we find a match, we return the position of the match.

C
#include <stdio.h>  int search(char *s, char *p) {     int i = 0, j = 0;      	// Traverse the string s     while (s[i] != '\0') {              	// Match the characters of p one by one         if (s[i] == p[j]) {             j++;                      	// If all characters are matched             if (p[j] == '\0') return 1;          } else j = 0;         i++;     }      	// If pattern is not found     return 0; }  int main() {     char s[] = "hello geeks";     char p[] = "geeks";      // Matching pattern p in string s     int res = search(s, p);     if (res)         printf("Found");     else         printf("Not found.");      return 0; } 

Output
Found

Next Article
How to Reverse a String in C?

A

anjalibo6rb0
Improve
Article Tags :
  • C Programs
  • C Language
  • C-String
  • C Examples

Similar Reads

  • How to Reverse a String in C?
    In C, a string is a sequence of characters terminated by a null character (\0). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C. Example: Inpu
    2 min read
  • How to Search in Array of Struct in C?
    In C, a struct (short for structure) is a user-defined data type that allows us to combine data items of different kinds. An array of structs is an array in which each element is of struct type. In this article, we will learn how to search for a specific element in an array of structs. Example: Inpu
    2 min read
  • Array of Pointers to Strings in C
    In C, arrays are data structures that store data in contiguous memory locations. Pointers are variables that store the address of data variables. We can use an array of pointers to store the addresses of multiple elements. In this article, we will learn how to create an array of pointers to strings
    2 min read
  • How to Split a String by a Delimiter in C?
    Splitting a string by a delimiter is a common task in programming. In C, strings are arrays of characters, and there are several ways to split them based on a delimiter. In this article, we will explore different methods to split a string by a delimiter in C. Splitting Strings in CThe strtok() metho
    2 min read
  • How to Find Length of a String Without string.h and Loop in C?
    C language provides the library for common string operations including string length. Otherwise, a loop can be used to count string length. But is there other ways to find the string length in C apart from above two methods. In this article, we will learn how to find length of a string without strin
    2 min read
  • How to Split a String by Multiple Delimiters in C?
    In C, strings are arrays of characters using string manipulation often requires splitting a string into substrings based on multiple delimiters. In this article, we will learn how to split a string by multiple delimiters in C. Example Input:char inputString[] = "Hello,World;This|is.GeeksForGeeks";ch
    2 min read
  • C Program to Split a String into a Number of Sub-Strings
    In this article, we will learn how to split a string into a number of sub-strings using the C program. The most straightforward method to split a string into substrings using a delimiter is by using strtok() function. Let’s take a look at an example: [GFGTABS] C #include <stdio.h> #include
    3 min read
  • How to store words in an array in C?
    We all know how to store a word or String, how to store characters in an array, etc. This article will help you understand how to store words in an array in C. To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index
    2 min read
  • How to Append a Character to a String in C?
    In this article, we will learn how to append a character to a string using the C program. The most straightforward method to append a character to a string is by using a loop traverse to the end of the string and append the new character manually. [GFGTABS] C #include <stdio.h> void addChar(ch
    3 min read
  • C Program to Find the Length of a String
    The length of a string is the number of characters in it without including the null character (‘\0’). In this article, we will learn how to find the length of a string in C. The easiest way to find the string length is by using strlen() function from the C strings library. Let's take a look at an ex
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences