Last Updated: June 7, 2026
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.
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.
count and set it to 0.count by 1.count.Input:
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.
s. The loop visits each character once.