Concepts / Operations on Strings

Operations on Strings

Substring extraction selects a sequence of characters from a string.

  • Programming

Why Extract Part of a String

Programs often receive a complete piece of text and need only a portion of it. A program might need the first few characters of a code, the ending of a word, or a middle block of text that sits between two known points. Operations on strings give you ways to pull out those pieces and to join pieces together. This article focuses on two of those ideas: extracting a substring with the substring method, and joining strings with the plus operator.

As you read, trace each example by hand before checking it. Work out which characters the method returns, then compare your answer with the result. Tracing positions carefully is the main skill this topic builds.

Counting Positions from Zero

Every character in a string has a position, and positions are counted starting from zero. The first character is at position 0, the second at position 1, and so on. The last character is at a position equal to the string length minus one. Because counting begins at zero, the numbers you use to point into a string are one less than the character numbers you would count with your fingers.

Hposition 0eposition 1lposition 2lposition 3oposition 4 (last)nextnextnextnext
Which character sits at position 0, position 3, and the last position of Hello, and how do the indexes line up with each character?

In the word Hello there are five characters, so the valid positions run from 0 to 4. Position 3 holds the second l, not the letter at the third place you might expect if you counted from one. Keeping this offset in mind prevents most errors in the sections that follow.

What a Substring Is

Definition

A substring is a sequence of characters that lies within a larger string. It is taken as a continuous block: the characters appear in the same order as in the original string and sit next to one another. Extracting a substring does not change the original string; it produces a new string made from some of its characters.

Substring extraction selects a sequence of characters from a string. The rest of this article explains how the positions you supply to the method determine which characters that sequence contains.

Stopping Before the End Index

The two-parameter form of substring takes a start position N and an end position M, written s1.substring(N,M). Extraction begins at position N and stops at position M, but the character at position M is not part of the result. The returned string holds the characters at positions N through M minus 1. This is an exclusive ending boundary.

Pposition 0ogrreturned substringrposition 1oposition 2, startgposition 3rposition 4aposition 5, end (excluded)mposition 6includedincludedincluded
Why does substring(2,5) return three characters rather than four, and which characters are included versus excluded between the start and end indexes?
Worked example

Extracting a middle block with substring(2,5)

Let s1 hold the word Program. What does s1.substring(2,5) return?

  1. 1
    Identify the start

    The first parameter is 2, so extraction begins at position 2, which holds the letter o.

  2. 2
    Identify the end

    The second parameter is 5. Position 5 holds the letter a, but it marks where extraction stops, not a character to include.

  3. 3
    List the included positions

    The method takes positions 2, 3, and 4, which are the characters o, g, and r.

  4. 4
    Count the result

    Three positions are included, so the result has three characters. The count equals 5 minus 2.

Result

ogr

Reading from a Start Position to the End

When substring has only one parameter, written s1.substring(N), the single value N identifies the starting position. The method returns the substring that begins at position N and continues until the end of the string. No end position is given, so the stopping point is simply the final character.

java
Output
ram
am
Notes on the code
  • substring(3) starts at position 3, the letter g, and runs to the end.
  • substring(5) starts at position 5, the letter a, and runs to the end.
  • Moving the starting position changes the result, but the end is always the last character.

Compare this with the two-parameter form. In substring(3) the result runs to the end because no ending position is supplied. Setting the starting position later shortens the result, and setting it earlier lengthens it, while the final character always remains included.

Joining Strings with the Plus Operator

Concatenation joins strings in the order you write them, using the plus operator. A single expression can mix fixed text, a variable, and more fixed text. In the source example, name is a String variable that already refers to the user's name, and the plus operator places the three pieces in the order they are written.

java
Output
Welcome, Ana!
Notes on the code
  • The fixed text Welcome, followed by a space is the first piece.
  • The variable name supplies the middle piece.
  • The exclamation mark is the final piece.
Before
String first = "Hello";
String second = "World";
String joined = first + second;

joined holds HelloWorld, with no space between the words.

After
String first = "Hello";
String second = "World";
String joined = first + " " + second;

joined holds Hello World, because a space string was added between the two pieces.

Concatenation adds exactly what you write and nothing more. If you need a space between two words, you must place a space inside a string literal in the expression. The plus operator will not insert one for you.

Mistakes Beginners Make with Substrings

  • Common mistake

    Assuming substring(N,M) includes the character at position M

    What it looks like
    s1.substring(2,5) on Program is expected to return ogra.
    Why it fails

    The returned string contains positions N through M minus 1. The ending position marks where extraction stops, so position 5 is not in the result.

    Do this instead

    Read the ending index as a stopping line. The result is ogr, with three characters.

  • Common mistake

    Counting positions from one instead of zero

    What it looks like

    Reading the third letter of Hello as position 3 and getting the second l instead of the letter at position 2.

    Why it fails

    Positions are counted starting from zero, so the first character is at position 0.

    Do this instead

    Label the first character 0 before choosing any index.

  • Common mistake

    Forgetting that concatenation adds no spaces

    What it looks like

    Joining Hello and World with the plus operator and expecting Hello World.

    Why it fails

    The plus operator places the pieces in the written order and adds only what is written.

    Do this instead

    Include a space inside a string literal, such as the text " ", wherever the output needs one.

Practice Tracing Substrings

MEDIUM

Let s1 hold the word Program. Before checking, predict the result of s1.substring(1,4) and then of s1.substring(4). Write out each included position and state which character the end index marks.

Hints
  • Start by listing the positions of P, r, o, g, r, a, m from 0 to 6.
  • For substring(1,4), include positions 1, 2, and 3 only.
  • For substring(4), begin at position 4 and continue to the last character.

Key Takeaways

  • A substring is a continuous sequence of characters taken from within a string, and string positions are counted starting from zero.
  • The two-parameter form substring(N,M) returns the characters at positions N through M minus 1, so the character at position M is excluded.
  • The one-parameter form substring(N) returns the characters from position N through the end of the string.
  • Concatenation with the plus operator joins pieces in the order written, so any required spaces must be included explicitly.