Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 495

17



  • strspn()

  • strpbrk()

  • strstr()


Thestrchr()Function ................................................................................

Thestrchr()function finds the first occurrence of a specified character in a string. The
prototype is
char *strchr(constchar *str, int ch);
The function strchr()searchesstrfrom left to right until the character chis found or
the terminating null character is found. If chis found, a pointer to it is returned. If not,
NULLis returned.
Whenstrchr()finds the character, it returns a pointer to that character. Knowing that
stris a pointer to the first character in the string, you can obtain the position of the
found character by subtracting strfrom the pointer value returned by strchr(). Listing
17.9 illustrates this. Remember that the first character in a string is at position 0. Like
many of C’s string functions,strchr()is case-sensitive and will, therefore, report that
the character “F”isn’t found in the string “raffle”.

LISTING17.9 strchr.c. Using strchr()to search a string for a single character
1: /* Searching for a single character with strchr(). */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: int main( void )
7: {
8: char *loc, buf[80];
9: int ch;
10:
11: /* Input the string and the character. */
12:
13: printf(“Enter the string to be searched: “);
14: gets(buf);
15: printf(“Enter the character to search for: “);
16: ch = getchar();
17:
18: /* Perform the search. */
19:
20: loc = strchr(buf, ch);
21:
22: if ( loc == NULL )

28 448201x-CH17 8/13/02 11:13 AM Page 495

Free download pdf