Swift example

How to get a substring in Swift

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

For the start or end of a string, use prefix(_:) and suffix(_:): s.prefix(5) is the first five characters, and asking for more than exist is safe. For anything in the middle, build String.Index values and slice: let i = s.index(s.startIndex, offsetBy: 7), then s[i...]. Swift strings have no Int subscript, so s[2] doesn't compile. A slice is a Substring; wrap it in String(…) to keep it.

In most languages a substring is s[2..5] or s.substring(2, 5). Swift doesn't let you index a string by number, because a Character can take anywhere from one to many bytes, and finding the fifth one means walking the string from the start. Instead you get prefix and suffix for the ends, String.Index positions for everything else, and search methods that hand you an index to slice at. Old answers that use substring(to:) or substringWithRange come from Swift 3 and earlier; the sections below show what replaced them, why a slice is a Substring, and a small safe extension for Int offsets, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1prefix, suffix, dropFirst and dropLastRecommended

Most substrings you need are anchored at one end: the first few characters, the last few, or everything after a known count. prefix(_:) and suffix(_:) take that many characters; dropFirst(_:) and dropLast(_:) remove that many and return the rest. None of them needs an index, and none of them crashes when the count is larger than the string: you get what exists. prefix(while:) and drop(while:) cut where a test stops being true. They are collection methods, so they work the same on arrays.

prefix.swift
let s = "Hello, world"

// First and last n characters
print(s.prefix(5))
print(s.suffix(5))

// Everything except the first or last n
print(s.dropFirst(7))
print(s.dropLast(7))

// Asking for more than there is is fine: you get what exists
print(s.prefix(50))
print("[\(s.dropFirst(50))]")

// Cut where a test stops being true
print(s.prefix(while: { $0.isLetter }))
print(s.drop(while: { $0 != " " }))

// The same calls work on arrays: the first 5 elements
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers.prefix(5))
print(type(of: numbers.prefix(5)))
print(Array(numbers.suffix(2)))

Output

prefix(5) and suffix(5) give Hello and world, and dropping seven characters from either end gives the same two words. prefix(50) returns the whole string and dropFirst(50) an empty one ([]), with no crash. prefix(while:) stops at the comma, and drop(while:) keeps everything from the first space, so world prints with its leading space. On an array, prefix(5) prints [10, 20, 30, 40, 50] but is an ArraySlice<Int>; wrap it in Array(…) when you need a real array.

2The nth character: index(_:offsetBy:)

s[2] is a compile error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead. A String.Index is a position in the string's storage, and you get one by walking from startIndex with index(_:offsetBy:). That walk is O(n), which is the cost the missing Int subscript would hide. Add limitedBy: to get nil instead of a crash past the end. If you read many characters by position, convert once to Array(s), a [Character] you can index by Int.

nth_character.swift
let word = "Swift"

// Walk from startIndex to the position, then subscript
let i = word.index(word.startIndex, offsetBy: 2)
print(word[i])

// Neighbours: index(after:) and index(before:)
print(word[word.index(after: word.startIndex)])
print(word[word.index(before: word.endIndex)])

// first and last are optionals: nil for an empty string
print(word.first ?? "-", word.last ?? "-")
print("".first ?? "-")

// limitedBy: returns nil instead of crashing past the end
if let j = word.index(word.startIndex, offsetBy: 10,
                      limitedBy: word.endIndex), j < word.endIndex {
    print(word[j])
} else {
    print("no character at offset 10")
}

// Many lookups? Copy to [Character] once, then index by Int
let chars = Array(word)
print(chars[0], chars[2], chars[4])

// A Character can span many bytes, so Int offsets need a walk
let thumbs = "a👍🏽b"
print(thumbs.count, thumbs.utf8.count, Array(thumbs)[1])

// A Character is not a String: convert when you need one
print(String(word[i]).uppercased())

Output

Offset 2 of Swift is i; index(after:) and index(before: endIndex) give w and t. endIndex is one past the last character, so it is not a valid subscript itself: that is why the limitedBy: check also tests j < word.endIndex. Without limitedBy:, offset 10 crashes here with Fatal error: String index is out of bounds. The emoji line shows why there is no Int subscript: 3 characters but 10 bytes, and Array(thumbs)[1] is the whole thumbs-up with its skin tone. Array(word) copies the string once (O(n)), after which each lookup is O(1).

3A range of characters with String.Index

To cut out the middle of a string, make a start and an end index, then subscript with a range: s[start..<end]. This is what replaced substringWithRange and substring(with:). The one-sided ranges s[..<i] and s[i...] replace substring(to:) and substring(from:). Compute the end from the start (index(start, offsetBy: n)) rather than from startIndex again, so the walk isn't repeated. For offsets that come from outside, wrap the index math in a function that uses limitedBy: and returns an optional.

range.swift
let s = "Hello, world"

// Characters 7 up to (not including) 12, like substring(with:)
let start = s.index(s.startIndex, offsetBy: 7)
let end = s.index(start, offsetBy: 5)
print(s[start..<end])

// One-sided ranges replace substring(to:) and substring(from:)
print(s[..<s.index(s.startIndex, offsetBy: 5)])
print(s[start...])

// A closed range includes the last index
print(s[s.startIndex...s.index(s.startIndex, offsetBy: 3)])

// limitedBy: returns nil instead of crashing past the end
func slice(_ text: String, from a: Int, length n: Int) -> String? {
    guard a >= 0, n >= 0,
          let lo = text.index(text.startIndex, offsetBy: a,
                              limitedBy: text.endIndex),
          let hi = text.index(lo, offsetBy: n, limitedBy: text.endIndex)
    else { return nil }
    return String(text[lo..<hi])
}
print(slice(s, from: 7, length: 5) ?? "nil")
print(slice(s, from: 7, length: 50) ?? "nil")
print(slice(s, from: 20, length: 1) ?? "nil")

Output

s[start..<end] with offsets 7 and 12 prints world, the two one-sided ranges print Hello and world, and the closed range ... includes offset 3, giving Hell. The slice helper returns world for a valid request and nil when either end runs past the string. If you'd rather clamp than fail, return endIndex in place of nil, as the extension in section 6 does.

4Substring vs String

Every slice above, from prefix to s[a..<b], returns a Substring, not a String. A Substring is a view into the original string: it shares its storage and its indices, so slicing copies nothing. The catch is that it keeps the whole original alive, so a five-character slice of a large file holds on to the large file. Convert with String(…) when you store the result or pass it to a function that takes a String; assigning a Substring to a String fails with cannot convert value of type 'String.SubSequence' (aka 'Substring') to specified type 'String'.

substring_type.swift
let s = "Hello, world"
let head = s.prefix(5)
print(type(of: head))

// A Substring shares the original's storage and indices
print(head.startIndex == s.startIndex)
let tail = s.dropFirst(7)
print(tail.startIndex == s.index(s.startIndex, offsetBy: 7))

// Convert with String(...) to keep it or pass it on
let word = String(head)
print(type(of: word), word)

func shout(_ text: String) -> String {
    text.uppercased()
}
print(shout(String(tail)))

// Or accept any StringProtocol and take both
func whisper<T: StringProtocol>(_ text: T) -> String {
    text.lowercased()
}
print(whisper(head), whisper(s))

Output

type(of: head) prints Substring. Both comparisons print true: the slice tail starts at the very index that is offset 7 in s, so an index taken from one works in the other. The first character of tail is tail[tail.startIndex], not position 0 of anything. String(head) makes an independent String. Writing your own function against StringProtocol, as whisper does, lets it take a String or a Substring without converting.

5Find a character, then slice

Often you don't know the offset, only the delimiter: everything before the @, everything after the =. firstIndex(of:) and lastIndex(of:) find a Character and return an optional String.Index, ready to slice with. range(of:) from Foundation finds a whole string and returns a Range, whose lowerBound and upperBound are the cut points (the standard library's firstRange(of:) does the same without the import). When you need the position as a number, distance(from:to:) converts an index back to an Int.

find.swift
import Foundation

let email = "[email protected]"

// firstIndex(of:) finds a Character and returns String.Index?
if let at = email.firstIndex(of: "@") {
    print(email[..<at])
    print(email[email.index(after: at)...])
    print("@ is at offset", email.distance(from: email.startIndex, to: at))
}

// lastIndex(of:) searches from the end
if let dot = email.lastIndex(of: ".") {
    print(email[dot...])
}

// range(of:) finds a whole string (it comes from Foundation)
let line = "key=value=more"
if let r = line.range(of: "=") {
    print(line[..<r.lowerBound], "|", line[r.upperBound...])
}

// Not found is nil, so the if let skips the body
print(email.firstIndex(of: "#") == nil)

// The text between two markers
let tag = "<title>Swift strings</title>"
if let open = tag.range(of: "<title>"),
   let close = tag.range(of: "</title>", range: open.upperBound..<tag.endIndex) {
    print(tag[open.upperBound..<close.lowerBound])
}

Output

Slicing up to the @ gives ada.lovelace; starting one index after it gives example.com, and distance(from:to:) reports @ is at offset 12. lastIndex(of: ".") finds the last dot, so the slice is .com. range(of:) stops at the first =, which splits the line into key and value=more. The second search in the last block starts after the opening tag, which matters when the markers could repeat. If you're cutting a string into many parts at every delimiter, split(separator:) is the better tool.

6A safe Int subscript extension

If your code reads characters by number in many places, a small extension on StringProtocol keeps the index math in one spot. This one uses argument labels, s[offset: 2] and s[offsets: 1..<4], so the call site doesn't look like an O(1) array lookup, and it never crashes: a single character comes back as an optional, and a range is clamped to the string. Because it extends StringProtocol, it works on Substring too.

safe_subscript.swift
extension StringProtocol {
    // text[offset: 2] is the third Character, or nil when out of range
    subscript(offset n: Int) -> Character? {
        guard n >= 0,
              let i = index(startIndex, offsetBy: n, limitedBy: endIndex),
              i != endIndex
        else { return nil }
        return self[i]
    }

    // text[offsets: 1..<4] by Int offsets, clamped to the string
    subscript(offsets r: Range<Int>) -> SubSequence {
        let r = r.clamped(to: 0..<Int.max)
        let lo = index(startIndex, offsetBy: r.lowerBound,
                       limitedBy: endIndex) ?? endIndex
        let hi = index(lo, offsetBy: r.count, limitedBy: endIndex) ?? endIndex
        return self[lo..<hi]
    }
}

let s = "Hello, world"
print(s[offset: 0] ?? "?")
print(s[offset: 4] ?? "?")
print(s[offset: 99] ?? "?")
print(s[offset: -1] ?? "?")
print(s[offsets: 7..<12])
print(s[offsets: 7..<99])
print("[\(s[offsets: 50..<60])]")
print(s[offsets: -3..<5])

// It works on a Substring too, counting from the slice's start
let tail = s.dropFirst(7)
print(tail[offset: 0] ?? "?")

Output

Offsets 0 and 4 give H and o; 99 and -1 give nil, printed as ?. The range form clamps instead: 7..<99 still prints world, a range entirely past the end is empty ([]), and -3..<5 is cut to 0..<5, giving Hello. On the slice s.dropFirst(7), offset 0 is w, the slice's own first character. Each call still walks the string, so in a loop over every position use Array(s) or iterate the string directly.

7Which should you use?

MethodOut of rangeBest for
s.prefix(n) / s.suffix(n)Returns what existsFirst or last n characters (and array elements)
s.dropFirst(n) / s.dropLast(n)Returns what existsEverything except the ends
s.firstIndex(of:) / s.range(of:)nil when not foundCutting before or after a delimiter
s.index(_:offsetBy:limitedBy:)nil past the endOffsets from user input or other data
s[s.index(s.startIndex, offsetBy: n)]CrashesOne character at an offset you know is valid
s[start..<end]Crashes on a bad indexA middle range, once you have the indices
Array(s)[n]CrashesMany random lookups by Int (one O(n) copy)
String(substring)n/aStoring a slice or passing it as a String

Frequently asked questions

Why can't I write s[0] or s[2] on a Swift string?

Because String has no Int subscript. The compiler says 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead. A Character can be several bytes (an emoji with a skin tone is one character), so reaching the nth one means walking the string. Use s[s.index(s.startIndex, offsetBy: 2)], or Array(s)[2] when you read many positions.

What replaced substring(to:), substring(from:) and substring(with:)?

Range subscripts. s.substring(to: i) is s[..<i], s.substring(from: i) is s[i...], and s.substring(with: a..<b) is s[a..<b]. With Foundation imported the old method still compiles here, with the warning 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upto' operator. For the first or last n characters, prefix(n) and suffix(n) need no index at all.

What is the difference between Substring and String?

A Substring is a view into another string: it shares the original's storage and indices, so slicing is cheap, but it keeps the whole original in memory. Every slice (prefix, dropFirst, s[a..<b]) returns one. Convert with String(slice) when you store the result or pass it to a function that takes a String; a function you write can take a generic StringProtocol parameter to accept both.

How do I get the index of a character as an Int?

Find it with firstIndex(of:), then measure from the start: s.distance(from: s.startIndex, to: i). For "[email protected]" that gives 12 for the @. Usually you don't need the number: slice with the String.Index directly, as in s[..<i].

What happens if index(_:offsetBy:) goes past the end?

The program crashes with Fatal error: String index is out of bounds. Subscripting with endIndex does the same, because endIndex is one past the last character. Use index(_:offsetBy:limitedBy:), which returns nil when the walk would pass the limit, or prefix(n), which just returns what exists.

How do I get the first 5 elements of an array?

numbers.prefix(5) works on arrays exactly as on strings and is safe when the array is shorter. It returns an ArraySlice<Int>; wrap it as Array(numbers.prefix(5)) when you need an Array. suffix(n), dropFirst(n) and dropLast(n) work the same way.

How do I convert between NSRange and Range<String.Index>?

With Foundation imported, Range(nsRange, in: s) turns an NSRange (from NSRegularExpression, for example) into an optional Range<String.Index>, and NSRange(range, in: s) goes the other way. NSRange(location: 7, length: 5) on "Hello, world" slices to world, and the range of "world" converts back to location 7, length 5.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground