Basics 0/97

Lesson 4 of 8

Strings

Count letters with 26 counters, check palindromes from both ends, and parse text in one left-to-right pass.

4,487 words · 20 min read

Part 1 of 10 Strings as arrays

Strings as arrays of characters

A string is stored the way an array of numbers is, with one character in each slot. The characters sit side by side in memory, each has an index counted from 0, and reading s[i] takes one step however long the string is. The computer stores each character as a number, its character code. Here is the word listen with the code of each of its characters:

index      0    1    2    3    4    5character  l    i    s    t    e    ncode       108  105  115  116  101  110

Because a string is an array, the algorithms that read an array of numbers also work on a string. Unlike most arrays of numbers, a string usually draws its characters from a small set. Lowercase words use only 26 different characters, and plain English text uses codes below 128, so a table with one entry for each possible character stays small however long the string is. The first three problems in this lesson are solved with such a table. If reading, slicing or building a string is new to you, Start coding's Strings lesson covers those operations.