Rolando Andrade
Back to Content

Strings in Programming: Length, Substrings and Concatenation: Programming Fundamentals (9)

Learn how strings work: characters, length, indexes, substrings, concatenation and upper case. Then traverse a string with a loop and convert roman numerals.

· 8 min read
Strings in Programming: Length, Substrings and Concatenation: Programming Fundamentals (9)

A string is a piece of text stored in a variable. It is a row of characters, one after another, and each character has a position. In this lesson you learn to measure a string, take characters and pieces out of it, join strings together and walk through a string one character at a time. At the end you write a program that turns a roman numeral like MCMXCIV into the number 1994.

In this lesson you will:

  • Measure a string with Length and change it with Upper and Lower.
  • Read one character with an index, like name[1].
  • Cut a piece of a string with Substring and join strings with + or Concat.
  • Traverse a string with a For loop to reverse it and count characters.
  • Convert roman numerals to numbers.

It takes about 35 minutes. You need a browser. Every example runs in the page.

Why text needs structure

Until now, every variable held one value. An Integer holds one number. A Char, one of the five basic types, holds one letter. But most data people care about is text: names, emails, passwords, messages, file names. A name like Rolando is seven letters that belong together. A string keeps them together in one variable, in order.

Because a string has an order, a program can ask questions about it. How long is it? What is the third letter? Does it contain an a? Is it before or after another word in the dictionary? You answer all of them with the few tools in this lesson and the loops you already know.

Strings also hide many bugs. Much of the code that AI agents write moves text around: it cleans input, builds messages and checks formats. When a generated function cuts the last letter off every name, you find the bug by knowing exactly where a string starts, where it ends and what each operation returns.

Characters inside a computer

A computer only stores numbers. To store text, it uses a table that gives every character a number. The oldest common table is ASCII, which has room for 128 characters in its standard part: English letters, digits, punctuation and a few control codes. It has no room for most other languages.

Unicode replaced it. Unicode gives a number to almost every character in every writing system, plus symbols and emojis. Its most used form, UTF-8, is compatible with ASCII, so old English text still works.

This table explains one surprise you will see soon. In ASCII and Unicode, all upper case letters come before all lower case letters. So for a computer, "B" comes before "a".

The tools for strings

These are the operations you use most. The examples use the string name <- "Rolando";.

Operation Pseudocode Result
Length Length(name) 7
Upper case Upper(name) "ROLANDO"
Lower case Lower(name) "rolando"
One character name[1] 'R'
A piece Substring(name, 1, 3) "Rol"
Join two strings "Hi " + name or Concat("Hi ", name) "Hi Rolando"
Compare "PERO" < "PERRO" True

An index is the number of a position. In StepCode, the first character is at index 1 and the last one is at index Length(name). Substring(text, from, to) returns the characters from position from to position to, and it includes both ends.

  • name[1] = 'R'
  • Substring(name, 1, 3) = "Rol"
  • Length(name) = 7
The string Rolando has seven characters at positions 1 to 7. Move from and to: name[from] picks one box, Substring picks the range, and Length counts all of them. Type your own name too.

Concatenation means joining strings end to end. It adds nothing between them. "perro" + "y" + "gato" gives "perroygato", with no spaces. If you want spaces, put them inside the quotes.

Comparison follows dictionary order, character by character. To compare "PERO" and "PERRO", the computer looks at the first position where they differ. That is position 4, where O meets R. O comes first in the alphabet, so "PERO" < "PERRO" is True. Two strings are equal only when every character matches.

"PERO" < "PERRO" is True. Position 4 is the first difference: 'O' (code 79) comes before 'R' (code 82).

The computer walks both strings until the first position where they differ, and that pair decides. Try apple and Banana: upper case B has a smaller code than lower case a.

Build programs with strings

Each part below is a complete program. Press Run, type the inputs shown, and compare your output.

1. Measure and cut a name

This program reads a name and applies every tool from the table.

Edit the code and press Run to try it.

Type Rolando.

You should see:

What is your name?
Length: 7
Upper case: ROLANDO
Lower case: rolando
First letter: R
Last letter: o
First three letters: Rol
Greeting: Hello, Rolando

Look at the last letter. name[Length(name)] works for a name of any size, because the last index is always the length.

2. Sort two words alphabetically

This exercise comes from the course slides. The program reads two words and writes them in dictionary order. Remember that upper case letters come before lower case ones. To compare fairly, the program compares the lower case version of both words.

Edit the code and press Run to try it.

Type perro and then Gato.

You should see:

Enter the first word:
Enter the second word:
Gato perro

Without Lower, the program would compare "perro" with "Gato". Upper case G comes before every lower case letter, so the result looks right here by luck. Try apple and Banana without Lower and the order breaks.

3. Reverse a string with a loop

To traverse a string means to visit every character, one by one, from index 1 to Length. A For loop does exactly that. This program from the course practice guide builds a new string, adding each character to the front, so the text comes out reversed.

Edit the code and press Run to try it.

Type Eso lo se.

You should see:

Enter a text:
The result is: es ol osE

After i = 9: reversed = "es ol osE"

Each iteration puts phrase[i] in front of reversed. The first letter ends up last, and the spaces move like any other character.

The variable reversed starts as the empty string "", a string with zero characters. Each iteration of the loop puts one more character in front of it. Spaces are characters too, so they move with the letters. You will reuse this loop in the mirror text exercise of Procedures and functions.

4. Count a character

The same traversal can count. This program asks for a text and a character, then counts how many times the character appears.

Edit the code and press Run to try it.

Type AAABBCABC and then C.

You should see:

Enter a text:
Enter a character:
2 repetitions

This pattern, a loop over every index with an If inside, is called a sequential search. You will use it again for arrays in the next lesson.

5. Insert and delete characters

In StepCode you cannot change one character of a string in place. To insert or delete, you build a new string from pieces. To turn "Pero" into "Perro", take the part before the new letter, add the letter, then add the part after it. To delete, join the part before and the part after, and skip the letter in the middle.

Edit the code and press Run to try it.

Press Run. This program needs no input.

You should see:

After inserting: Perro
After deleting: Pero

To insert at the very end, the first piece is the whole word and the second piece is empty. The same code still works.

6. Convert roman numerals to numbers

This was Activity 3 of the course. Roman numerals use seven symbols: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500 and M is 1000. Usually you add the symbols from left to right: LVIII is 50 + 5 + 3 = 58. But when a smaller symbol comes before a larger one, you subtract it. IV is 4 and CM is 900.

The program traverses the numeral and remembers the value of the previous symbol. When the previous value is smaller than the current one, it subtracts the previous value. Otherwise it adds it. After the loop, it adds the last value.

Edit the code and press Run to try it.

Type MCMXCIV.

You should see:

Enter a roman numeral: 
MCMXCIV is 1994

Follow it by hand once, with a trace table if it helps. M adds nothing yet and remembers 1000. C (100) is smaller, so 1000 is added. M (1000) is larger than 100, so 100 is subtracted. That is how CM becomes 900. Try III and LVIII too. You should get 3 and 58.

Common mistakes

If you see Index 0 is outside "word": its positions run from 1 to 7., it means you used index 0. In StepCode, the first character is at index 1. Start your loops at 1.

If you see Index 8 is outside "word": its positions run from 1 to 7., your loop goes one step too far. The last valid index is Length(word), so the loop must end there, not at Length(word) + 1.

If you see A single letter of a text cannot be changed; build the new text with "Substring" and "Concat"., it means you wrote something like word[1] <- 'P';. Build a new string from pieces, like in part 5.

If you see "+" does not mix text and numbers: convert the number with "ToText"., it means you tried "Total: " + 5. Convert the number first: "Total: " + ToText(5). Or use a comma in Write, which accepts mixed values.

If a variable named text gives strange errors like I did not expect "text" here., it is because Text is a type name in StepCode, like String. Pick another name, like phrase.

Strings and their neighbors

A string looks like a Char and like an array, but it is neither.

Type Holds Example
Char Exactly one character 'A'
String Zero or more characters in order "Ana" or ""
Array of Char A fixed number of boxes you can change one by one the next lesson

Indexes also change between languages. Pseudocode in this course starts at 1. Python starts at 0, and its slices leave out the last index:

name = "Rolando"
print(len(name))     # 7
print(name[0])       # R  (the first character is at index 0)
print(name[0:3])     # Rol (from 0 up to 3, without 3)
print(name.upper())  # ROLANDO

When you read code written by a person or an AI agent, check the index base first. Most off by one bugs start there.

Practice exercises

These exercises come from the course practice guide for strings. Try each one in an empty editor first. Then compare with the solution.

Remove the vowels

Write a program that removes every vowel from a text.

Input This is a text gives:

Enter a text:
Result: Ths s  txt
Edit the code and press Run to try it.

Alternate upper and lower case

Write a program that turns even positions to upper case and odd positions to lower case.

Input Hello gives:

Enter a text:
Result: hElLo
Edit the code and press Run to try it.

Mix two texts

Write a program that mixes two texts character by character. When one text runs out, add the rest of the other one.

Inputs PQRTE and ABC give:

Text 1:
Text 2:
The result is PAQBRCTE
Edit the code and press Run to try it.

Challenge: hangman

This was Workshop 2 of the course. Build the hangman game. One player types a secret word and a number of attempts. The other player guesses one letter per turn. Show the word with underscores for the hidden letters, the letters already used and the attempts left. A wrong letter costs one attempt. A repeated letter costs nothing. Upper and lower case count as the same letter.

Inputs apple, 3, then the letters a, p, l, a, e give:

Enter the secret word:
Enter the number of attempts:
_____   Used letters:    Attempts left: 3
Enter a letter:
a____   Used letters: a   Attempts left: 3
Enter a letter:
app__   Used letters: ap   Attempts left: 3
Enter a letter:
appl_   Used letters: apl   Attempts left: 3
Enter a letter:
Letter already used
appl_   Used letters: apl   Attempts left: 3
Enter a letter:
You win! The word is apple
Edit the code and press Run to try it.

The hangman uses every idea in this lesson: it builds a string in a loop, searches a string, and replaces one character with two Substring calls and concatenation.

All the editors on this page run on StepCode, the pseudocode language I built for my students at UCAB.

What you learned

  • A string is a row of characters. Each character has an index, from 1 to Length(text) in StepCode.
  • Upper and Lower change the case, Substring(text, from, to) cuts a piece, and + or Concat joins strings without adding spaces.
  • Strings compare in dictionary order, and upper case letters come before lower case ones.
  • A For loop from 1 to Length traverses a string. With an If inside, it searches and counts.
  • You insert and delete characters by joining pieces of the old string.

Next steps

A string holds a row of characters. In the next lesson, arrays, you store a row of any type: ten numbers, five names or a list of grades. You will load them, traverse them, search them and find the largest and smallest value.