Skip to content
Swift

String Manipulation

Trim, split, join, replace, and index strings using Swift's Unicode API.

By EZ4Code Team
stringtext

Code

import Foundation

let raw = "  Hello, Swift World!  "

// Trimming
let trimmed = raw.trimmingCharacters(in: .whitespaces)
print(trimmed)

// Splitting
let parts = "a,b,,c".split(separator: ",").map(String.init)
print(parts)

// Joining
let joined = ["x", "y", "z"].joined(separator: "-")
print(joined)

// Replacing
let replaced = "hello".replacingOccurrences(of: "l", with: "L")
print(replaced)

// Subscript with index
let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 2)
print(s[i])                  // i
let range = s.startIndex..<i
print(s[range])              // Sw

// Multi-line string
let multi = """
Line 1
Line 2
"""
print(multi)

// Formatting numbers
let pi = String(format: "%.2f", 3.14159)
print(pi)

// Date formatting
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
print(fmt.string(from: Date()))

Explanation

Swift strings are Unicode-correct collections of grapheme clusters, so indexing uses String.Index rather than integers. Helpers like trimmingCharacters, split, joined, and replacingOccurrences cover the common string operations. String(format:) and DateFormatter bridge to the C-style format and locale-aware date formatting.

More Swift Snippets