AP® Computer Science Principles · Big Idea 3 · Topic 3.4

Strings, Concatenation, and Substrings

Concatenation glues two strings together end to end to make one longer string, treating everything as text, never as numbers to add. A substring pulls out a piece of a string by character position.

Concatenation takes two strings and places the second one right after the first, with nothing added or removed in between. The string 12 concatenated with 34 gives 1234, because the computer is not doing math, it is stacking characters: 1, 2, then 3, 4, read left to right. This is true no matter what the strings contain. Concatenating 7 and 3 gives 73, not 10, because concatenation never looks at the content and decides to add. It only knows how to lay text end to end.

Because of this, the string 7 and the number 7 are not the same value. The number 7 can be added, multiplied, compared with greater-than. The string 7 is just a character, and combining it with other strings only ever extends the text. A program that reads input as a string must explicitly convert it to a number before doing arithmetic with it, otherwise concatenation sneaks in where addition was expected.

A substring pulls a piece out of an existing string using starting and ending positions, rather than building a new string from scratch. Concatenating COMP with UTER gives COMPUTER, and taking the first four characters of that gives back COMP. Asking for characters 3 through 5 of a 4 character string pushes past the end, since position 5 does not exist, which is the kind of boundary case that shows up constantly once strings are stored in lists or processed in loops, the next step in this unit.

Key terms

Concatenation
Joining two strings end to end to form one new, longer string.
Substring
A shorter string taken from part of a longer string, chosen by character position.
String
A sequence of characters, such as letters, digits, or symbols, treated as text.
Index
A number giving the position of a character within a string, used to select substrings.

Watch it explained

  1. How it worksHow does concatenation build a brand new string by laying two strings end to end?
  2. Worked exampleFind the result of concatenating COMP with UTER and then taking the first four characters.
  3. Going furtherWhat changes about a substring request that asks for characters 3 through 5 of a 4 character string?
  4. Common mistakeWhy isn't the string 7 the same value as the number 7?

Check yourself

Your turn1 of 2
A string of length 21 is concatenated with a string of length 20. What is the length of the resulting string?

End of topic.