But what if we want to work with data that isn’t a number? We can represent other forms of data as a string.
Strings are any sequence of characters (letters, spaces, numbers, or symbols). While almost anything can be a string, they are typically used to represent text or speech. Similar to how we represent speech in writing, we surround strings with single ('...'
) or double quotes ("..."
).
But why the name strings? Strings are a sequence of symbols, so we can think of the characters being strung together, like beads in a necklace.
So, what can we use strings for?
- To display data that uses text or symbols, like printing our name to the screen.
- To add or remove text. Since strings are a linear sequence of characters, we can break strings into even smaller strings, or combine strings to make longer ones.
- To modify characters. For example, we could capitalize the first letter of every word in a string if we wanted to turn it into a title.
- To let the computer communicate with us in a “human-readable” way, like displaying the rules of an online game.
Strings may sometimes look similar to other data types. But it’s important to remember that even if a number looks like a number, or a boolean looks like a boolean, it’s good to check that it’s not a string — or else you won’t be able to use it correctly!
Take the following string: '20'
. The string '20'
is different from the numerical value of 20
. While they appear to be the same, a computer would see the first as two characters: '2'
and '0'
, while the second contains the numerical value of 20
.
Instructions
While we can think of strings as chunks of text, it’s also useful to remember that they’re just a collection of individual characters, like letters in a banner.
Type a word into the box and see the result. Notice how each character is separate from the ones around it, but they come together to make a word!