Summary - String functions
- C course
- Beginner
- Lesson 93/116
- 5 min
Combine strchr, strtok and sprintf to write a CSV parser.
Summary - String functions
In this group you learned five core string functions. strchr searches a single character, strstr searches a substring. strtok splits the string by delimiters. sprintf writes formatted into a buffer, sscanf reads formatted from a string.
char *p = strchr(s, 'a');
char *q = strstr(s, "he");
char *t = strtok(s, ",");
sprintf(buf, "%d", n);
sscanf(s, "%d", &n);They all come with the <string.h> or <stdio.h> header. Do not forget return values and NULL checks. Now you will do an exercise that uses several of them together.
Practice Count comma-separated fruits
Split "elma,armut,muz" by commas with strtok. Loop over the pieces with a while loop; increment a count counter for each piece. After the loop, print count with printf. Include the <string.h> header.
Starter code
#include <stdio.h>
int main(void) {
char text[] = "elma,armut,muz";
/* Split with strtok; loop with while; count; print with printf */
return 0;
}Sample solution
#include <string.h>
int count = 0;
char *tok = strtok(text, ",");
while (tok != NULL) {
count++;
tok = strtok(NULL, ",");
}
printf("%d\n", count);Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match function to task
| Term | Meaning |
|---|---|
strchr |
Searches a character |
strstr |
Searches a substring |
strtok |
Splits into pieces |
sprintf |
Writes to a string |
sscanf |
Reads from a string |
2 Which function is used to find a substring?
- strchr
- strstr Correct answer
- strtok
- sprintf
Explanation: strstr searches for one string inside another.
3 Fill in the blank: split the string
char *tok = ____(text, ",");
char *tok = strtok(text, ",");
Explanation: strtok splits the string by delimiters.