String helpers
- C course
- Intermediate
- Lesson 14/116
- 6 min
Add and test string processing functions.
String helpers
The second lesson defines str_len and str_is_empty. str_len returns the byte count of a string; str_is_empty tells whether the string is empty.
For str_len you walk to the end of the string and count characters. str_is_empty calls str_len and compares the result to zero. This avoids code duplication: a single length function serves both length and emptiness checks. The main from the previous lesson is included in the starting code; you add the new functions.
str_len implementation
str_len walks to the end of the string and counts. The most natural form is a while (*s) loop; at the string end *s becomes zero and the loop exits.
Example: int str_len(const char *s) { int n = 0; while (*s) { n++; s++; } return n; }. Each step increments n and advances s. The loop stops at '\0'. This pattern is common in C; the standard strlen works similarly.
Practice Add str_len and str_is_empty
Below the existing declarations, write int str_len(const char *s); count the string length with a while (*s) loop and return it. Write int str_is_empty(const char *s) that returns str_len(s) == 0. In main add printf("%d\n", str_len("Merhaba")); and printf("%d\n", str_is_empty(""));.
Starter code
#include <stdio.h>
int str_len(const char *s);
int str_is_empty(const char *s);
int num_abs(int n);
int num_sign(int n);
int arr_max(int *a, int n);
int arr_sum(int *a, int n);
int main(void) {
printf("Modül hazır\n");
return 0;
}
// str_len fonksiyonunu yaz: dize boyunu döndür
// str_is_empty fonksiyonunu yaz: boy 0 ise 1, değilse 0
// main içinde ikisini çağır ve yazdırSample solution
#include <stdio.h>
int str_len(const char *s);
int str_is_empty(const char *s);
int num_abs(int n);
int num_sign(int n);
int arr_max(int *a, int n);
int arr_sum(int *a, int n);
int str_len(const char *s) {
int n = 0;
while (*s) { n++; s++; }
return n;
}
int str_is_empty(const char *s) {
return str_len(s) == 0;
}
int main(void) {
printf("Modül hazır\n");
printf("%d\n", str_len("Merhaba"));
printf("%d\n", str_is_empty(""));
return 0;
}Expected output
Modül hazır 7 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the string helpers
| Term | Meaning |
|---|---|
str_len("Merhaba") |
7 (string length) |
str_len("") |
0 (empty string) |
str_is_empty("") |
1 (empty) |
str_is_empty("x") |
0 (non-empty) |
2 Which loop is most natural for str_len?
- while (*s) Correct answer
- do...while
- for (int i=0; i<n; i++)
- switch
Explanation: while (*s) walks to the string end; it's the natural choice.
3 Complete the str_len loop
int str_len(const char *s) {
int n = 0;
while (____) { n++; s++; }
return n;
}
int str_len(const char *s) {
int n = 0;
while (*s) { n++; s++; }
return n;
}
Explanation: *s stays non-zero until the string end.