Swift String Manipulation
Introduction
String manipulation is a fundamental skill in programming that involves modifying, combining, or extracting parts of text data. In Swift, the String type offers a rich set of functionalities for text manipulation that makes working with textual data straightforward yet powerful.
In this tutorial, you'll learn various techniques to manipulate strings in Swift, from basic operations like concatenation and character access to more complex operations like substring extraction and transformations.
Basic String Operations
String Concatenation
One of the most common string operations is combining two or more strings together. Swift offers multiple ways to accomplish this.
Using the + Operator
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
print(fullName) // Output: John Doe
Using String Interpolation
String interpolation is a more readable approach when combining strings with variables:
let firstName = "Jane"
let lastName = "Smith"
let fullName = "\(firstName) \(lastName)"
print(fullName) // Output: Jane Smith
Using the append() Method
For mutable strings, you can use the append()
method:
var greeting = "Hello"
greeting.append(", World!")
print(greeting) // Output: Hello, World!
Accessing Characters in a String
Swift treats strings as collections of characters, allowing for direct access.
let message = "Swift"
// Access the first character
let firstChar = message[message.startIndex]
print(firstChar) // Output: S
// Access the last character
let lastIndex = message.index(before: message.endIndex)
let lastChar = message[lastIndex]
print(lastChar) // Output: t
For accessing characters at specific positions, you need to use string indices:
let message = "Hello"
let index = message.index(message.startIndex, offsetBy: 2)
let thirdChar = message[index]
print(thirdChar) // Output: l
Working with Substrings
Extracting Substrings
Swift provides various ways to extract portions of a string:
Using Ranges
let greeting = "Hello, World!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let firstPart = greeting[..<index]
print(firstPart) // Output: Hello
Using prefix() and suffix()
let message = "Swift Programming"
let firstFive = message.prefix(5)
let lastFour = message.suffix(4)
print(firstFive) // Output: Swift
print(lastFour) // Output: ming
Important Note About Substrings
In Swift, when you extract a substring, the result is of type Substring
, not String
. A Substring
shares memory with its original String, which makes it efficient but temporary:
let original = "Swift Programming"
let substring = original.prefix(5) // Type is Substring
// Convert back to String when storing for longer use
let newString = String(substring)
String Transformations
Changing Case
Swift makes it easy to transform the case of strings:
let normalText = "Hello, Swift Programmers!"
let lowercased = normalText.lowercased()
print(lowercased) // Output: hello, swift programmers!
let uppercased = normalText.uppercased()
print(uppercased) // Output: HELLO, SWIFT PROGRAMMERS!
let capitalized = normalText.capitalized
print(capitalized) // Output: Hello, Swift Programmers!
Replacing Content
You can replace parts of a string with other content:
let oldMessage = "Swift is difficult"
let newMessage = oldMessage.replacingOccurrences(of: "difficult", with: "awesome")
print(newMessage) // Output: Swift is awesome
Trimming Whitespace
To remove unwanted whitespace from the beginning and end of strings:
let paddedText = " Too much space "
let trimmed = paddedText.trimmingCharacters(in: .whitespaces)
print("'\(trimmed)'") // Output: 'Too much space'
Searching Within Strings
Checking if a String Contains Another String
let sentence = "Swift is a powerful programming language"
// Check if contains a substring
let containsSwift = sentence.contains("Swift")
print(containsSwift) // Output: true
// Check if starts with a prefix
let startsWithSwift = sentence.hasPrefix("Swift")
print(startsWithSwift) // Output: true
// Check if ends with a suffix
let endsWithLanguage = sentence.hasSuffix("language")
print(endsWithLanguage) // Output: true
Finding the Position of a Substring
let text = "Finding needle in haystack"
if let range = text.range(of: "needle") {
let position = text.distance(from: text.startIndex, to: range.lowerBound)
print("Found 'needle' at position \(position)") // Output: Found 'needle' at position 8
}
Practical Examples
Example 1: Building a Username Validator
This example shows how to validate a username by checking its length and allowed characters:
func isValidUsername(_ username: String) -> Bool {
// Check if length is between 3 and 15 characters
guard username.count >= 3 && username.count <= 15 else {
return false
}
// Check if contains only letters, numbers, and underscores
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")
return username.unicodeScalars.allSatisfy { allowedCharacters.contains($0) }
}
// Test the function
let username1 = "john_doe42"
let username2 = "user@name"
let username3 = "a"
print(isValidUsername(username1)) // Output: true
print(isValidUsername(username2)) // Output: false (contains @)
print(isValidUsername(username3)) // Output: false (too short)
Example 2: Formatting a Phone Number
This example shows how to format a plain string of digits into a standard phone number format:
func formatPhoneNumber(_ phoneNumber: String) -> String {
// Remove any non-digit character
let digits = phoneNumber.filter { $0.isNumber }
// Check if we have the expected number of digits
guard digits.count == 10 else {
return "Invalid phone number"
}
// Convert to array for easier manipulation
let characters = Array(digits)
// Format as (XXX) XXX-XXXX
return "(\(characters[0])\(characters[1])\(characters[2])) \(characters[3])\(characters[4])\(characters[5])-\(characters[6])\(characters[7])\(characters[8])\(characters[9])"
}
// Test the function
let rawPhoneNumber = "1234567890"
let formattedPhoneNumber = formatPhoneNumber(rawPhoneNumber)
print(formattedPhoneNumber) // Output: (123) 456-7890
Example 3: Creating a Simple Text Statistics Tool
This example counts words, characters, and sentences in a text:
func textStatistics(for text: String) -> (wordCount: Int, characterCount: Int, sentenceCount: Int) {
// Count characters (excluding whitespace)
let characterCount = text.filter { !$0.isWhitespace }.count
// Count words
let words = text.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty }
let wordCount = words.count
// Count sentences (simple approximation based on periods)
let sentenceCount = text.components(separatedBy: ".").filter { !$0.isEmpty }.count
return (wordCount, characterCount, sentenceCount)
}
// Test the function
let sampleText = "Swift is amazing. It makes iOS development fun. Let's learn more about it!"
let stats = textStatistics(for: sampleText)
print("Word count: \(stats.wordCount)") // Output: Word count: 14
print("Character count: \(stats.characterCount)") // Output: Character count: 59
print("Sentence count: \(stats.sentenceCount)") // Output: Sentence count: 3
Summary
String manipulation is an essential skill in Swift programming. In this tutorial, we've covered:
- Basic string operations like concatenation using
+
, string interpolation, and theappend()
method - Accessing individual characters in strings using indices
- Extracting substrings with ranges,
prefix()
, andsuffix()
- String transformations including case changes, content replacement, and whitespace trimming
- Searching within strings using
contains()
,hasPrefix()
, andhasSuffix()
- Practical examples that demonstrate real-world applications
Understanding these string manipulation techniques will help you handle text data effectively in your Swift applications, whether you're building iOS apps, macOS applications, or server-side Swift services.
Additional Resources
Exercises
To practice your string manipulation skills, try these exercises:
- Write a function that reverses a string without using the built-in
reversed()
method. - Create a function that checks if a string is a palindrome (reads the same forward and backward).
- Implement a function that censors specified words in a text by replacing them with asterisks.
- Write a function that extracts all hashtags from a social media post.
- Create a simple URL parser that extracts the domain name from a URL string.
Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)