Arrays and strings · Exercise 10 of 100

Counting a Character

Start a counter at zero and visit each character of the string once. Increase the counter only on an exact match, so a run of matching letters contributes once per letter.

Try it yourself

How many times does the lowercase letter s occur in mississippi?

One-step hint

Trace mississippi from left to right and put a separate dot under each s, including neighboring ones. Count the dots.

Worked solution
  1. Read the first four letters, miss. The adjacent s letters raise the counter from zero to two.
  2. The remaining letters, issippi, contain another pair of s letters. That brings the count to 4.
DSA compiler

Explore the idea visually in the character frequency lab.