String Functions in Swift

The standard library’s String type provides many useful string-related methods. Here are some examples to give you a sense of the available functionality.

import Foundation

// We alias print to a shorter name as we'll use it a lot below.
let p = print

func main() {
    // Here's a sample of the methods available on String.
    // In Swift, these are methods on the String object itself,
    // so we call them directly on the string in question.
    // You can find more methods in the Swift documentation.

    p("Contains:  ", "test".contains("es"))
    p("Count:     ", "test".filter { $0 == "t" }.count)
    p("HasPrefix: ", "test".hasPrefix("te"))
    p("HasSuffix: ", "test".hasSuffix("st"))
    p("Index:     ", "test".firstIndex(of: "e")?.utf16Offset(in: "test") ?? -1)
    p("Join:      ", ["a", "b"].joined(separator: "-"))
    p("Repeat:    ", String(repeating: "a", count: 5))
    p("Replace:   ", "foo".replacingOccurrences(of: "o", with: "0"))
    p("Replace:   ", "foo".replacingOccurrences(of: "o", with: "0", options: [], range: "foo".startIndex..<"foo".index("foo".startIndex, offsetBy: 2)))
    p("Split:     ", "a-b-c-d-e".split(separator: "-"))
    p("ToLower:   ", "TEST".lowercased())
    p("ToUpper:   ", "test".uppercased())
}

main()

When you run this program, you’ll see:

$ swift string-functions.swift
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      ["a", "b", "c", "d", "e"]
ToLower:    test
ToUpper:    TEST

In Swift, many of these operations are methods on the String type itself, rather than functions in a separate package. This makes the syntax slightly different from the original example, but the functionality is very similar.

Note that Swift’s String is Unicode-correct and works with extended grapheme clusters, which can make some operations more complex but also more accurate for international text. The Index operation, for example, is more complicated in Swift due to this Unicode-correctness.

The Replace operation with a limit is not directly available in Swift, so we’ve simulated it by using a range for the second example.