Created
February 10, 2010 23:30
-
-
Save dwf/300985 to your computer and use it in GitHub Desktop.
Demonstrates the use of strchr(), written for a tutorial.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Demonstrates the use of strchr to count the number of spaces in a string | |
| * entered by the user. | |
| * | |
| * Prepared for tutorial purposes by David Warde-Farley, CSC209H Winter 2008 | |
| */ | |
| #include <stdio.h> | |
| #include <string.h> | |
| #define BUFSIZE 100 | |
| int | |
| main() | |
| { | |
| char buf[BUFSIZE]; | |
| int numspaces = 0; /* To keep track of the number of spaces. */ | |
| char *ptr; /* A pointer to move through the string with. */ | |
| printf("Enter a string: "); | |
| fgets(buf, BUFSIZE, stdin); | |
| /* Ask strchr to find the first space */ | |
| ptr = strchr(buf, ' '); | |
| /* | |
| * strchr will return NULL when it gets to the end of the string | |
| * and finds no more spaces. | |
| */ | |
| while (ptr != NULL) | |
| { | |
| numspaces++; | |
| printf("Returned by strchr: %s", ptr); | |
| /* | |
| * Get us past the space we just found by incrementing | |
| * our pointer by one; without this we loop forever. | |
| */ | |
| ptr++; | |
| /* Let strchr find the next space. */ | |
| ptr = strchr(ptr, ' '); | |
| } | |
| printf("\nFound %d spaces in your string.\n", numspaces); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment