wael.blog

Where I talk about anything and everything Code!

20, Aug 2024

Solving Common String Problems

Okay, so sometimes the little things matter a whole lot, it may sound odd but I've found great benefit in taking a break from the big stuff and returning to the bare basics every once in a while. So let's play around a bit with one of these basics: Strings.
You’ve probably spent some time wrangling with strings. Strings are fundamental in programming, but they can be a bit tricky to handle at times. Whether you're just starting out or have been coding for a while, mastering string manipulation is essential. Today, we’re going to explore some common string problems and how to solve them using Swift. So grab your coffee you beautiful nerd ...




1. Basic String Operations



Before the complex stuff, let’s cover some basics. Swift provides a range of powerful tools for string manipulation. Here are a few essential operations:

1.1 Concatenation



Combining strings is a frequent task. In Swift, you can concatenate strings using the `+` operator or the `append` method.

Example:

let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
print(fullName) // Output: John Doe


Or, using `append`:

var greeting = "Hello"
greeting.append(", World!")
print(greeting) // Output: Hello, World!


Or use the returning, non-mutating `appending` variation:

let greeting = "Hello"
print(greeting.appending(", World!")) // Output: Hello, World!


1.2 Substrings



Sometimes, you need to extract a part of a string. Swift makes this easy with substrings.

Example:

let sentence = "Hello, Swift World!"
let index = sentence.index(sentence.startIndex, offsetBy: 7)
let substring = sentence[index...] // "Swift World!"
print(substring)


Here, `index` gives us the starting point of the substring which is 7 positions from the `startIndex`. The `string[Range]` syntax slices the string from that index to the end. When we say `[index...]` we say Range from the index to the end of the string.

Can you use the same method to extract "Hello, Swift" instead?

2. Handling Special Characters



Special characters like newline (`\n`), tab (`\t`), or Unicode characters often come into play. Let's see how we can handle these.

2.1 Escaping Characters



In Swift, you need to escape special characters with a backslash. For instance, to include a newline character:

Example:

let multiLineString = "Hello, World!\nWelcome to Swift programming."
print(multiLineString)
// Output:
// Hello, World!
// Welcome to Swift programming.


2.2 Unicode Characters



Swift supports Unicode, so you can use special characters from various languages, even emojis.

Example:

let unicodeString = "Swift is awesome! 🌟"
print(unicodeString) // Output: Swift is awesome! 🌟


3. Searching and Replacing Text



Finding and replacing text is a common need. Swift offers methods for searching and replacing substrings.

3.1 Searching for a Substring



You can use `range(of:)` to search for a substring within a string.

Example:

let text = "Hello, Swift!"
if let range = text.range(of: "Swift") {
    let from = text.distance(from: text.startIndex, to: range.lowerBound)
    let to = text.distance(from: text.startIndex, to: range.upperBound) - 1
    print("Found 'Swift' at range From: \(from) To: \(to)")
} else {
    print("'Swift' not found")
}


Notice the two lines we used to calculate the from/to positions. Swift is somewhat unique to other languages when it comes to calculating string ranges and string indices. Make sure to set some time aside to getting familiar with those.

3.2 Replacing Substrings



To replace occurrences of a substring, use the `replacingOccurrences(of:with:)` method.

Example:

var message = "Hello, World!"
message = message.replacingOccurrences(of: "World", with: "Swift")
print(message) // Output: Hello, Swift!


4. String Formatting



Formatting strings is crucial for displaying information correctly. It's actually rare where you find yourself using strings without some kind of formatting.

4.1 Interpolation



Swift provides string interpolation to embed variables into strings.

Example:

let name = "Alice"
let age = 30
let formattedString = "Name: \(name), Age: \(age)"
print(formattedString) // Output: Name: Alice, Age: 30


Handy, no? You can actually interpolate any object this same exact way, all you need to do is override the implementation of `description` for the object.

4.2 Custom Formatting



For more complex formatting, you can use `String(format:)`.

Example:

let temperature = 23.456
let formattedTemperature = String(format: "Temperature: %.2f°C", temperature)
print(formattedTemperature) // Output: Temperature: 23.46°C


This is the classic way of formatting strings, most other languages support this same style so make sure to be familiar with it if you plan on trying out other languages in the future.




5. String case manipulation



5.1 Changing to Uppercase/Lowercase



You can easily convert strings to uppercase or lowercase.

Example:

let originalString = "Swift Programming"
let uppercaseString = originalString.uppercased()
let lowercaseString = originalString.lowercased()
print(uppercaseString) // Output: SWIFT PROGRAMMING
print(lowercaseString) // Output: swift programming


5.2 Capitalizing Words



To capitalize the first letter of each word, use `capitalized`.

Example:

let title = "swift programming for beginners"
let capitalizedTitle = title.capitalized
print(capitalizedTitle) // Output: Swift Programming For Beginners


These operations are usually useful when converting dictionary keys to display titles, or for example when you are matching strings together, you usually want to lowercase-compare both strings first so that "UppER" = "uPPer" and so on.

6. Trimming and Padding Strings



Sometimes you need to clean up or adjust the length of strings.

6.1 Trimming Whitespace



Use `trimmingCharacters(in:)` to remove leading and trailing whitespace or other characters.

Example:

let paddedString = "   Hello, Swift!   "
let trimmedString = paddedString.trimmingCharacters(in: .whitespaces)
print(trimmedString) // Output: Hello, Swift!


If you deal with API responses, usually this API deals with a DB in the end which may have some white space padding to some of its entries! More common than I'd like to admit but true non-the less. So trimming strings in this way may be an insurance against any weird spacing or padding appearing in your UI and you're non the wiser that it's an extra space from the backend.

6.2 Padding Strings



To pad a string to a certain length, you can use `padding(toLength:withPad:startingAt:)`.

Example:

let original = "Swift"
let padded = original.padding(toLength: 10, withPad: " ", startingAt: 0)
print(padded) // Output: "Swift     "


Sometimes your backend requires that values are of an exact length. Or maybe you wrote a particular function that relies on the input always being 10 characters. Admittedly, I didn't come across many real world use-cases for this.

7. Splitting and Joining Strings



7.1 Splitting Strings



The `components(separatedBy:)` method divides a string into an array of substrings.

Example:

let csv = "apple,banana,cherry"
let fruits = csv.components(separatedBy: ",")
print(fruits) // Output: ["apple", "banana", "cherry"]


Many mahy times, you may come across API responses that give you an array of items like this that you need to split apart yourself, however, make sure that the special separating character does not appear in any of the items themselves; a common pitfall of using spaces as a separator. e.g. "Apple Orange Star Fruit" ("Star Fruit" should be one item but splitting by " " will separate them incorrectly).

7.2 Joining Strings



To join an array of strings back into a single string, use `joined(separator:)`.

Example:

let fruitsArray = ["apple", "banana", "cherry"]
let csvString = fruitsArray.joined(separator: ",")
print(csvString) // Output: apple,banana,cherry


Same as with separation, joining may also be used with some APIs or if you are constructing CSV data. Remember, just like in separation, to consider your separators carefully before joining.

8 Regular Expressions



Regular expressions can be used for pattern matching.

Example:

import Foundation

let regex = try! NSRegularExpression(pattern: "\\d+")
let text = "The year is 2024"
let matches = regex.matches(in: text, range: NSRange(location: 0, length: text.utf16.count))

for match in matches {
    let range = match.range
    let matchString = (text as NSString).substring(with: range)
    print("Found number: \(matchString)")
}
// Output: Found number: 2024


Regular expressions are a whole world of its own, you'll even find yourself using reqex while doing a simple search in your IDE. Make sure to get familiar with regex as much as you can as it's indispensable to your career as a developer.




Keep experimenting with these techniques and soon you'll find string manipulation in Swift to be a breeze. Make sure to feel good by trying tem out, seeing them work and then forgetting about them. Remember, revisiting the basics always keeps your mind and memory sharp, no matter how rudimentary it may be.

Interested in what I do? get in touch

Contacts

wael.studio

×
About Services Skills Projects Blog Contact