← Exercises|

Walking a string

Write10 of 14 · about 7 min

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?

Not graded — this is for you.

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.