C strstr() Function
Photo Credit to CodeToFun
đ Introduction
In the C programming language, working with strings is a common and essential task.
The strstr()
function is part of the C Standard Library (<string.h>) and is used for string searching.
It locates the first occurrence of a substring within another string and returns a pointer to the beginning of the found substring.
In this tutorial, we'll explore the usage and functionality of the strstr()
function in C.
đĄ Syntax
The syntax for the strstr()
function is as follows:
char *strstr(const char *haystack, const char *needle);
- haystack: The string to be searched.
- needle: The substring to search for within the haystack.
đ Example
Let's dive into an example to illustrate how the strstr()
function works.
#include <stdio.h>
#include <string.h>
int main() {
const char * haystack = "This is a simple example.";
const char * needle = "simple";
// Search for the substring
char * result = strstr(haystack, needle);
// Output the result
if (result != NULL) {
printf("Substring found: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}
đģ Output
Substring found: simple example.
đ§ How the Program Works
In this example, the strstr()
function is used to search for the substring "simple" within the string "This is a simple example."
âŠī¸ Return Value
The strstr()
function returns a pointer to the first occurrence of the needle in the haystack. If the needle is not found, it returns NULL.
đ Common Use Cases
The strstr()
function is particularly useful when you need to determine if a specific substring exists within a larger string and locate its position. It's commonly employed in scenarios where you want to extract or manipulate portions of text.
đ Notes
- The
strstr()
function is case-sensitive, meaning that it distinguishes between uppercase and lowercase letters. - If you need a case-insensitive search, you can use other functions or manually convert the strings to lowercase (or uppercase) before calling
strstr()
.
đĸ Optimization
The strstr()
function is optimized for efficiency. However, for large strings and frequent searches, consider storing the result in a variable if you need to use it multiple times to avoid redundant computations.
đ Conclusion
The strstr()
function in C is a powerful tool for searching for substrings within strings. It provides flexibility in dealing with different types of data and enables conditional logic based on the result.
Feel free to experiment with different strings and substrings to deepen your understanding of the strstr()
function. Happy coding!
đ¨âđģ Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (C strstr() Function) please comment here. I will help you immediately.