Explain String Searching with programm

Explain String Searching with example

The library also provides several string searching functions:
char *strchr(const char *string, int c) -- Find first occurrence of character c in string.
char *strrchr(const char *string, int c) -- Find last occurrence of character c in string.
char *strstr(const char *s1, const char *s2) -- locates the first occurrence of the string s2 in string s1.
char *strpbrk(const char *s1, const char *s2) -- returns a pointer to the first occurrence in string s1 of any character from string s2, or a null pointer if no character from s2 exists in s1
size_t strspn(const char *s1, const char *s2) -- returns the number of characters at the begining of s1 that match s2.
size_t strcspn(const char *s1, const char *s2) -- returns the number of characters at the begining of s1 that do not match s2.
char *strtok(char *s1, const char *s2) -- break the string pointed to by s1 into a sequence of tokens, each of which is delimited by one or more characters from the string pointed to by s2.
char *strtok_r(char *s1, const char *s2, char **lasts) -- has the same functionality as strtok() except that a pointer to a string placeholder lasts must be supplied by the caller.
strchr() and strrchr() are the simplest to use, for example:
char *str1 = "Hello";
char *ans;

ans = strchr(str1,'l');
After this execution, ans points to the location str1 + 2
strpbrk() is a more general function that searches for the first occurrence of any of a group of characters, for example:
char *str1 = "Hello";
char *ans;

ans = strpbrk(str1,'aeiou');
Here, ans points to the location str1 + 1, the location of the first e.
strstr() returns a pointer to the specified search string or a null pointer if the string is not found. If s2 points to a string with zero length (that is, the string ""), the function returns s1. For example,
char *str1 = "Hello";
char *ans;

ans = strstr(str1,'lo');
will yield ans = str + 3.
strtok() is a little more complicated in operation. If the first argument is not NULL then the function finds the position of any of the second argument characters. However, the position is remembered and any subsequent calls to strtok() will start from this position if on these subsequent calls the first argument is NULL. For example, If we wish to break up the string str1 at each space and print each token on a new line we could do:
char *str1 = "Hello Big Boy";
char *t1;


for ( t1 = strtok(str1," ");
      t1 != NULL;
      t1 = strtok(NULL, " ") )

printf("%s\n",t1);
Here we use the for loop in a non-standard counting fashion:
•    The initialisation calls strtok() loads the function with the string str1
•    We terminate when t1 is NULL
•    We keep assigning tokens of str1 to t1 until termination by calling strtok() with a NULL first argument.

Labels: