Walking a string
A C string is not a type. It is an array of characters with a 0 byte on the end, and a char * is just the address of its first character. Everything in <string.h> works by walking forward until it finds that 0.
That is why strlen costs time proportional to the length of the string, and why calling it in a loop condition walks the whole string on every single pass.
A character is a small integer. s[i] gives you the number; comparing it with 'a' compares it with the number that letter stands for.
Example
const char *s = "hi";
/* s[0] is 'h', s[1] is 'i', s[2] is 0 — the terminator */
int len = 0;
while (s[len] != '\0') {
len++;
}Your task
Write int count_vowels(const char *s) returning how many of a, e, i, o, u the string contains, counting both cases. Do not call strlen: walk to the terminator.
- ·Do not use
strlen— walk to the terminator yourself
Stuck?
Explain it
Why is for (int i = 0; i < strlen(s); i++) a bad habit even though it works?
Where this goes
Project 6 builds string utilities by hand for exactly this reason: you cannot use them well until you have written them once.
This is a teaching runtime for a subset of C, running in your browser on a 32-bit model machine. It reports mistakes a real compiler lets through — reading uninitialised memory, running off an array, signed overflow — and it is not the compiler your project uses.
Press Run to see what your program does, or Check when you think it is right. Everything runs here in your browser.