---
title: "Strings in Programming: Length, Substrings and Concatenation: Programming Fundamentals (9)"
date: "2026-10-11"
description: "Learn how strings work: characters, length, indexes, substrings, concatenation and upper case. Then traverse a string with a loop and convert roman numerals."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-strings/"
author: "Rolando Andrade"
---

# 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.

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](/blog/programming-fundamentals-variables-and-data-types/#the-five-basic-data-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](/blog/programming-fundamentals-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.

*Figure: 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.

*Figure: 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.

**Part 1: string basics** (StepCode)

```stepcode
Program StringBasics
    Define name As String;

    Write "What is your name?";
    Read name;

    Write "Length: ", Length(name);
    Write "Upper case: ", Upper(name);
    Write "Lower case: ", Lower(name);
    Write "First letter: ", name[1];
    Write "Last letter: ", name[Length(name)];
    Write "First three letters: ", Substring(name, 1, 3);
    Write "Greeting: ", Concat("Hello, ", name);
EndProgram
```

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.

**Part 2: alphabetical order** (StepCode)

```stepcode
Program AlphabeticalOrder
    Define first, second As String;

    Write "Enter the first word:";
    Read first;
    Write "Enter the second word:";
    Read second;

    If Lower(first) < Lower(second) Then
        Write first, " ", second;
    Else
        Write second, " ", first;
    EndIf
EndProgram
```

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.

**Part 3: reverse a text** (StepCode)

```stepcode
Program ReverseText
    Define phrase, reversed As String;
    Define i As Integer;

    Write "Enter a text:";
    Read phrase;

    reversed <- "";
    For i <- 1 To Length(phrase) Step 1 Do
        reversed <- phrase[i] + reversed;
    EndFor

    Write "The result is: ", reversed;
EndProgram
```

Type `Eso lo se`.

You should see:

```
Enter a text:
The result is: es ol osE
```

*Figure: 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](/blog/programming-fundamentals-procedures-and-functions/#exercise-2-mirror-text).

### 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.

**Part 4: count a character** (StepCode)

```stepcode
Program CountCharacter
    Define phrase As String;
    Define letter As Char;
    Define i, count As Integer;

    Write "Enter a text:";
    Read phrase;
    Write "Enter a character:";
    Read letter;

    count <- 0;
    For i <- 1 To Length(phrase) Step 1 Do
        If phrase[i] = letter Then
            count <- count + 1;
        EndIf
    EndFor

    Write count, " repetitions";
EndProgram
```

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](/blog/programming-fundamentals-arrays/#4-search-for-a-word).

### 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.

**Part 5: insert and delete** (StepCode)

```stepcode
Program InsertAndDelete
    Define word, before, after As String;

    word <- "Pero";
    before <- Substring(word, 1, 2);
    after <- Substring(word, 3, Length(word));
    word <- before + "r" + after;
    Write "After inserting: ", word;

    before <- Substring(word, 1, 2);
    after <- Substring(word, 4, Length(word));
    word <- before + after;
    Write "After deleting: ", word;
EndProgram
```

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.

**Part 6: roman numerals** (StepCode)

```stepcode
Program RomanNumerals
    Define roman As String;
    Define i, value, previous, result As Integer;

    Write "Enter a roman numeral: ";
    Read roman;

    result <- 0;
    previous <- 0;

    For i <- 1 To Length(roman) Step 1 Do
        Switch roman[i] Do
            'M':
                value <- 1000;
            'D':
                value <- 500;
            'C':
                value <- 100;
            'L':
                value <- 50;
            'X':
                value <- 10;
            'V':
                value <- 5;
            'I':
                value <- 1;
        EndSwitch

        If previous < value Then
            result <- result - previous;
        Else
            result <- result + previous;
        EndIf

        previous <- value;
    EndFor

    result <- result + previous;
    Write roman, " is ", result;
EndProgram
```

Type `MCMXCIV`.

You should see:

```
Enter a roman numeral: 
MCMXCIV is 1994
```

Follow it by hand once, with a [trace table](/blog/programming-fundamentals-sequential-structures/#trace-a-program-by-hand) 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:

```python
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
```

**Solution: remove the vowels** (StepCode)

```stepcode
Program RemoveVowels
    Define phrase, result As String;
    Define letter As Char;
    Define i As Integer;

    Write "Enter a text:";
    Read phrase;

    result <- "";
    For i <- 1 To Length(phrase) Step 1 Do
        letter <- Lower(phrase[i]);
        If letter <> 'a' And letter <> 'e' And letter <> 'i' And letter <> 'o' And letter <> 'u' Then
            result <- result + phrase[i];
        EndIf
    EndFor

    Write "Result: ", result;
EndProgram
```

### 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
```

**Solution: alternate case** (StepCode)

```stepcode
Program AlternateCase
    Define phrase, result As String;
    Define i As Integer;

    Write "Enter a text:";
    Read phrase;

    result <- "";
    For i <- 1 To Length(phrase) Step 1 Do
        If i Mod 2 = 0 Then
            result <- result + Upper(phrase[i]);
        Else
            result <- result + Lower(phrase[i]);
        EndIf
    EndFor

    Write "Result: ", result;
EndProgram
```

### 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
```

**Solution: mix two texts** (StepCode)

```stepcode
Program MixTwoTexts
    Define first, second, mixed As String;
    Define i As Integer;

    Write "Text 1:";
    Read first;
    Write "Text 2:";
    Read second;

    mixed <- "";
    i <- 1;
    While i <= Length(first) And i <= Length(second) Do
        mixed <- mixed + first[i] + second[i];
        i <- i + 1;
    EndWhile
    While i <= Length(first) Do
        mixed <- mixed + first[i];
        i <- i + 1;
    EndWhile
    While i <= Length(second) Do
        mixed <- mixed + second[i];
        i <- i + 1;
    EndWhile

    Write "The result is ", mixed;
EndProgram
```

### 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
```

**Solution: hangman** (StepCode)

```stepcode
Program Hangman
    Define secret, state, used As String;
    Define letter As Char;
    Define attempts, i As Integer;
    Define found, alreadyUsed As Boolean;

    Write "Enter the secret word:";
    Read secret;
    secret <- Lower(secret);
    Write "Enter the number of attempts:";
    Read attempts;

    state <- "";
    For i <- 1 To Length(secret) Step 1 Do
        state <- state + "_";
    EndFor
    used <- "";

    While state <> secret And attempts > 0 Do
        Write state, "   Used letters: ", used, "   Attempts left: ", attempts;
        Write "Enter a letter:";
        Read letter;
        letter <- Lower(letter);

        alreadyUsed <- False;
        For i <- 1 To Length(used) Step 1 Do
            If used[i] = letter Then
                alreadyUsed <- True;
            EndIf
        EndFor

        If alreadyUsed Then
            Write "Letter already used";
        Else
            used <- used + letter;
            found <- False;
            For i <- 1 To Length(secret) Step 1 Do
                If secret[i] = letter Then
                    state <- Substring(state, 1, i - 1) + letter + Substring(state, i + 1, Length(state));
                    found <- True;
                EndIf
            EndFor
            If Not found Then
                attempts <- attempts - 1;
            EndIf
        EndIf
    EndWhile

    If state = secret Then
        Write "You win! The word is ", secret;
    Else
        Write "You lose. The word was ", secret;
    EndIf
EndProgram
```

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](/projects/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](/blog/programming-fundamentals-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.
