Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use String Slicing in Swift
Written by Team Kodeco

In Swift, you can use string slicing to extract a substring from a given string. String slicing allows you to access a range of characters in a string, you can use the substring(with:) method to extract a substring from a string.

Here’s how to use string slicing in Swift:

let greeting = "Hello, World!"

// You can extract a substring using a range of indices
let startSkip = "Hello, ".count
let endSkip = "!".count
let startIndex = greeting.index(greeting.startIndex, offsetBy: startSkip)
let endIndex = greeting.index(greeting.endIndex, offsetBy: -endSkip)
let range = startIndex..<endIndex
let substring = greeting[range]
print(substring) // Output: "World"

You can also use the prefix(_:) and suffix(_:) methods to extract substrings:

let prefix = greeting.prefix(5)
print(prefix) // Output: "Hello"

let suffix = greeting.suffix(6)
print(suffix) // Output: "World!"
© 2024 Kodeco Inc.