Extracting Substrings in Swift

Some programming languages provide a Substring method in the String class to extract parts of a string. In Swift, however, Substring is a data type, not a method.

In this article, we'll go over how to extract substrings from a string in Swift.

Extracting a Substring from the Beginning of a String

To extract a substring from the beginning of a string in Swift, you can use the prefix() method.

It takes the number of characters as an argument and returns that many characters from the beginning as a Substring.

If the number specified is larger than the string's length, it simply returns the entire string instead of throwing an error.

Passing a negative value will result in an error.

Since the return value is a Substring (which references the original string), you can create a new String by passing it into the String initializer.


Let's use the prefix() method to extract the first 5 characters of a string:

let s1 = "ABCDEFGHIJKLMN"
let sub1 = String(s1.prefix(5))
print(sub1)

let s2 = "ABC"
let sub2 = String(s2.prefix(5))
print(sub2)

The output looks like this. If there are at least 5 characters, it returns 5; otherwise, it returns all characters up to the end:

ABCDE
ABC

Extracting a Substring from the End of a String

To extract a substring from the end of a string, you can use the suffix() method.

It works the same way as prefix(), except it takes characters from the end of the string.


Here's an example using suffix() to get the last 5 characters:

let s1 = "ABCDEFGHIJKLMN"
let sub1 = String(s1.suffix(5))
print(sub1)

let s2 = "ABC"
let sub2 = String(s2.suffix(5))
print(sub2)

The output shows the last 5 characters being extracted:

JKLMN
ABC

Extracting a Substring from a Specific Position

In other languages, the Substring method often lets you specify a starting index (and sometimes an ending index or length) to extract part of a string.

Swift does not provide such a method directly, but you can achieve the same by working with string indexes.

Below are some sample codes showing how to extract substrings using indexes.

Extracting a Substring Starting from a Specific Position

Here's how you can extract a substring starting at a specific index. For example, starting at index 3:

let s = "ABCDEFGHIJKLMN"
let start = 3

let startIdx = s.index(s.startIndex, offsetBy: start, limitedBy: s.endIndex) ?? s.endIndex
let sub = String(s[startIdx...])

print("sub = \(sub)")

Line 4 uses the index() method to get the position of the starting index as a String.Index.

The limitedBy parameter prevents the offset from going past the string's end. Without it, specifying a value beyond the end would cause an error.

If the offset is out of range, nil is returned, and we fall back to endIndex, which represents the position just past the last character.

Then, on line 5, s[startIdx...] returns the substring starting at startIdx, and we wrap it with String() to create a new String.

Note: just like with prefix(), specifying a negative index will cause an error.


The output looks like this, showing that everything from index 3 (D) onward is extracted:

sub = DEFGHIJKLMN

Extracting a Substring Between a Start and End Position

Now let's see how to extract a substring between a start and end index. For example, from index 3 to 6:

let s = "ABCDEFGHIJKLMN"
let start = 3
let end = 6

var sub = ""

if start > end {
    sub = ""
} else {
    let startIdx = s.index(s.startIndex, offsetBy: start, limitedBy: s.endIndex) ?? s.endIndex
    let endIdx = s.index(s.startIndex, offsetBy: end + 1, limitedBy: s.endIndex) ?? s.endIndex
    sub = String(s[startIdx..<endIdx])
}

print("sub = \(sub)")

Here we calculate both the start and end String.Index values and slice the string between them before converting to a String.

If start is negative, it will throw an error. You may want to check the value beforehand and adjust as needed.


The output shows that the substring from index 3 to 6 is extracted:

sub = DEFG

Extracting Substrings in Swift 1


That's it for extracting substrings from String in Swift.