AlgoMaster Logo

Length of a String

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

The length of a string is the count of characters it holds. Most languages expose this through a built-in helper, but the exercise is to compute it yourself.

Think of a string as a row of boxes, each holding one character. The string "hello" fills five boxes: h, e, l, l, o. Spaces and digits live in boxes too, so "open ai" holds seven characters: o, p, e, n, the space, a, and i.

Key Constraints:

  • The string can be empty → An empty string has no characters, so its length is 0. A counter that starts at 0 returns this correctly, because the loop never runs.
  • Spaces and digits count → Every character occupies one position, so a space or a digit adds to the length just like a letter does.

Approach 1: Character Loop

Intuition

Start a counter at 0 and walk across the string from the first character to the last, adding 1 for each character. When there are no more characters to visit, the counter holds the answer.

Starting the counter at 0 rather than 1 is what makes the empty string work. When s is "", the loop body never runs, so the counter keeps its starting value of 0.

Algorithm

  1. Create a counter named count and set it to 0.
  2. Move through the string one index at a time, from the first character to the last.
  3. At each character, increase count by 1.
  4. After the loop finishes, return count.

Example Walkthrough

Input:

0
h
1
e
2
l
3
l
4
o
s

The counter starts at 0. You visit h and it becomes 1, then e and it becomes 2, then the first l for 3, the second l for 4, and finally o for 5. There are no more characters, so the loop ends and you return 5.

5
result

Code