use strstr() which returns a pointer to the start of the leftmost occurrence of the second string in the first one. Then if strstr() returns a non-null result, use pointer arithmetic to calculate the character index:
=========================
#include
main() {
char *s1 = "red blue green";
char *s2 = "blue";
char *s3 = strstr( s1, s2 );
if (s3) printf("String starts at position %ld\n", s3 - s1);
else printf("String not found");
}
=========================
This prints "4" because "blue" starts at s1[4].
?
2016-10-07 01:52:07 UTC
Substring In C
Venkatesh Sun
2011-07-23 22:18:18 UTC
There are numerous functions available in C to achieve the purpose of finding different positions of a substring with a string.
strstr():
To obtain the first occurrence of substring in a string the function used is strstr().
The header file that must be included while using this function strstr() is
In the above the function strstr() returns a pointer to the first occurrence of str2 in str1. If no match is found then NULL is returned.
strrstr():
This function is used to obtain the last occurrence of substring in a string.
The syntax for this function is
strrstr(const char *s, const char *subs );
The header file that must be included while using the function strrstr() is
This returns a pointer which points to the last occurrence of a substring within another string. If the substring is not found, this will be the NULL pointer.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.