iOS Swift: String Examples

By:   –  Last updated:   –  #ios ·  #swift

Code Theme [Dark]

Content Overview [Hide]

A quick guide about Swift String by examples.

1 How to Create a String in Swift

Creating an empty string.

let str1: String = ""
let str2 = String()
str1.isEmpty    // true
str2.isEmpty    // true

Creating a string from a character.

let aChar: Character = "A"
let str3 = String(aChar)    // "A"

Creating a string from another string.

let str4 = "Hello"
let str5 = String(str4)

Creating a string according to a given format.

let str6: String = String(format: "Price of %@ is $%.2f", "apple", 1.5)
// "Price of apple is $1.50"

Read file content as a string.

if let filePath = Bundle.main.path(forResource: "demo", ofType: "txt"),
    let fileContent: String = try? String(contentsOfFile: filePath, encoding: .utf8) {
    print(fileContent)
}

2 How to Format a String in Swift

Changing upper or lower case.

let str7 = "Hello, I am a fox."
str7.capitalized        // "Hello, I Am A Fox."
str7.uppercased()       // "HELLO, I AM A FOX."
str7.lowercased()       // "hello, i am a fox."

Formatting with string interpolation.

let fruit = "orange"
let price: Float = 3.45
let description = "Price of \(fruit) is $\(price)"
// "Price of orange is $3.45"

Using C-style printf formatting string.

let hour = 8
let min = 5
let second = 23
let time = String(format: "Current time is %02d:%02d:%02d", hour, min, second)
// "Current time is 08:05:23"

Trimming a string.

let str8 = "   so many spaces with a new line  ----    \n"

/* Trim spaces */
str8.trimmingCharacters(in: .whitespaces)
// "so many spaces with a new line  ----    \n"


/* Trim spaces and newlines */
str8.trimmingCharacters(in: .whitespacesAndNewlines)
// "so many spaces with a new line  ----"


/* Trim characters specified in a set */
let charsToBeTrimmed = CharacterSet(charactersIn: "- \n")
str8.trimmingCharacters(in: charsToBeTrimmed)
// "so many spaces with a new line"

3 Length

let str9 = "é is a French letter"

str9.isEmpty    // false

str9.characters.count       // 20
str9.lengthOfBytes(using: .utf8)    // 21

4 Index

let str15 = "Never trouble about trouble until TROUBLE troubles you!"
str15.contains("about")     // true
str15.hasPrefix("Ne")       // true
str15.hasSuffix("!")        // true

Start index and end index.

str15.characters.count      // 55
str15.startIndex            // 0
str15.endIndex              // 55

startIndex is the position of the first character of a string, endIndex is the position AFTER the last character in a string. So you can not use endIndex as a string’s subscript.

/* OK, access the first character */
str15[str15.startIndex]

/* Error, crash */
str15[str15.endIndex]

It is easy to get the indices before and after a given index.

/* The position of the second character */
let i: String.Index = str15.index(after: str15.startIndex)
str15[i]    // "e"

/* The position of the last character */
let j: String.Index = str15.index(before: str15.endIndex)
str15[j]    // "!"

Also, it is possible to get an index farther away from the given index by calling index(_:offsetBy:).

let forwardIdx: String.Index = str15.index(str15.startIndex, offsetBy: 5)
str15.substring(to: forwardIdx)     // "Never"

let backwardIdx: String.Index = str15.index(str15.endIndex, offsetBy: -4)
str15.substring(from: backwardIdx)  // "you!"

/* nil, because outside of the string’s range */
let idx: String.Index? = str15.index(backwardIdx, offsetBy: 8, limitedBy: str15.endIndex)

5 Range

let str16 = "Jingle bells, jingle bells, JINGLE bells"
str16.characters.count  // 40

Searching a range forward in a string.

let r1: Range<String.Index>? = str16.range(of: "jingle")
r1?.lowerBound          // 14
r1?.upperBound          // 20

Searching a range backward in a string with caseInsensitive option.

let r2: Range<String.Index>? = str16.range(of: "jingle", options: [.backwards, .caseInsensitive], range: nil, locale: nil)
r2?.lowerBound          // 28
r2?.upperBound          // 34

6 Substring

let str17 = "cat, dog, fish, bird"

Getting a substring with a String.Index.

let offsetIndex1: String.Index = str17.index(str17.startIndex, offsetBy: 5)
let offsetIndex2: String.Index = str17.index(str17.endIndex, offsetBy: -6)
str17.substring(from: offsetIndex1)     // "dog, fish, bird"
str17.substring(to: offsetIndex2)       // "cat, dog, fish"

Getting a substring with a sub range (Range<String.Index>)

let subRange: Range<String.Index> = offsetIndex1..<offsetIndex2
str17.substring(with: subRange)         // "dog, fish"

7 Modifying a String

7.1 Concatenating and Appending a String in Swift

Concatenating strings

var str10 = "Tom is a cat."
let str11 = "Jerry is a mouse."

let str12 = str10 + " " + str11

str10 += " Wow!"
print(str10)

Appending content to a string.

The appendingXXX methods will not change the string itself

/* let */
let str13 = "Today is Monday. "

str13.appending("I have to work. ")
// "Today is Monday. I have to work. "

str13
// "Today is Monday."


str13.appendingFormat("Current time is %02d:%02d:%02d", 9, 5, 15)
// "Today is Monday. Current time is 09:05:15"

str13
// "Today is Monday."

The append method will change the string in-place.

/* var */
var str14 = "Today is Sunday. "

str14.append("I can have a rest. ")
// "Today is Sunday. I can have a rest. "

str14
// "Today is Sunday. I can have a rest. "


str14.appendingFormat("Current time is %02d:%02d:%02d", 9, 5, 15)
// "Today is Sunday. I can have a rest. Current time is 09:05:15"


str14
// "Today is Sunday. I can have a rest. "

7.2 Inserting

Inserting a single character into a string at a specified index.

var str18 = "Apple, Google, Microsoft"
str18.insert(",", at: str18.endIndex)   // "Apple, Google, Microsoft,"
str18.insert(" ", at: str18.endIndex)   // "Apple, Google, Microsoft, "

Inserting a collection of characters into a string at a specified index.

str18.insert(contentsOf: "Facebook".characters, at: str18.endIndex)
// "Apple, Google, Microsoft, Facebook"

Note: inserting methods will change the string in-place.

7.3 Removing

Removing a single character from a string at a specified index.

var str19 = "iOS, Android"
str19.remove(at: str19.startIndex)  // "i"
str19   // "OS, Android"

Removing a substring at a given range.

let delSubRange = str19.startIndex..<str19.index(str19.startIndex, offsetBy: 4)
str19.removeSubrange(delSubRange)   // "Android"

Emptying a string.

str19.removeAll()
str19
str19.isEmpty

Note: removing methods will change the string in-place.

7.4 Replacing

Replacing a substring with another string.

let str20 = "iPhone, iPad, IPAD mini, iWatch"

str20.replacingOccurrences(of: "iPad", with: "iPad Tablet")
// "iPhone, iPad Tablet, IPAD mini, iWatch"


str20.replacingOccurrences(of: "iPad", with: "iPad Tablet", options: .caseInsensitive, range: nil)
// "iPhone, iPad Tablet, iPad Tablet mini, iWatch"


str20
// "iPhone, iPad, IPAD mini, iWatch"

Replacing a given range with another string.

/* let */
let str21 = "Office: Excel, Word, PowerPoint"
/* var */ 
var str22 = "Office: Excel, Word, PowerPoint"

let replaceRange = str21.startIndex..<str21.index(str21.startIndex, offsetBy: 6)

str21.replacingCharacters(in: replaceRange, with: "iWork")
// "iWork: Excel, Word, PowerPoint"


str21
// "Office: Excel, Word, PowerPoint"


str22.replaceSubrange(replaceRange, with: "iWork")
// "iWork: Excel, Word, PowerPoint"


str22
// "iWork: Excel, Word, PowerPoint"

Note: replacingCharacters(in:with:) will not change the original string; replaceSubrange(_:with:) will change the string in-place.