Sams Teach Yourself C in 21 Days

(singke) #1

Thestrspn()Function ................................................................................


This function is related to the previous one,strcspn(), as the following paragraph
explains. Its prototype is
size_t strspn(const char *str1, const char *str2);
The function strspn()searchesstr1, comparing it character by character with the char-
acters contained in str2. It returns the position of the first character in str1that doesn’t
match a character in str2. In other words,strspn()returns the length of the initial seg-
ment of str1that consists entirely of characters found in str2. The return is 0 if no char-
acters match. Listing 17.11 demonstrates strspn().

LISTING17.11 strspn.c. Searching for the first nonmatching character with strspn()
1: /* Searching with strspn(). */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: int main( void )
7: {
8: char buf1[80], buf2[80];
9: size_t loc;
10:
11: /* Input the strings. */
12:
13: printf(“Enter the string to be searched: “);
14: gets(buf1);
15: printf(“Enter the string containing target characters: “);
16: gets(buf2);
17:
18: /* Perform the search. */
19:
20: loc = strspn(buf1, buf2);
21:
22: if ( loc == 0 )
23: printf(“No match was found.\n”);
24: else
25: printf(“Characters match up to position %d.\n”, loc-1);
26: return 0;
27: }

Enter the string to be searched: How now Brown Cow?
Enter the string containing target characters:How now what?
Characters match up to position 7.

498 Day 17

OUTPUT

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

Free download pdf