Workshop 14: Common String Manipulation Methods

The workshop focus on teaching you how to use just a handful of the Foundation framew’s methods to manipulate Swift string variables and constants. I encourage you to use the Variable.playground file you added in the iOS Swift Variable project to practice Swift code presented in the workshop.

Before you begin, I assume you’ve done the following:

The Foundation framework contain many classes and methods you can use in a playground and Swift class file. The framework class and methods are written in the Objective-C language. To use the framework, you have to  add this import statement in your playground file or your Swift class file.

import Foundation

The compiler behind the scene convert the Foundation framework classes and methods to swift modules; thus enabling you to use Swift syntax to access the framework classes and methods in your playground and Swift class file.

String Formatting Methods

The Swift Programming language provide many string formatting methods; however, in this section you learn how to use only three of them.

NSString()
This string formatting method takes two or more parameters and return a Swift String object. It is the Swift version of the Objective-C stringWithFormat: method. Here is an example of how to use it in a playground file.

var totalPrice = 99.90
NSString(format: "Product price $%.2f", totalPrice)

Output
99.9
“Product price $99.90”

stringByAppendingString()
This method appends (joins) two Swift string objects. Code below shows how to use the method in a playground file.

// Declare and initialize two Swift String objects
var stringOne = "Bananas are a good source of vitamin C, "
var stringTwo = "Potassium, and dietary fiber."

// Join the string objects, then assign the result to a variable
var message = stringOne.stringByAppendingString(stringTwo)

Output
“Bananas are a good source of vitamin C, ”
“Potassium, and dietary fiber.”
“Bananas are a good source of vitamin C, Potassium, and dietary fiber.”

stringByAppendingFormat()
This method format a string object and append it to the end of the first string object.

// Declare and initial the first string object
let question = "What time is it? "
let answer = "It is 8:23 am."

// Format the second string object and append it to the end of the first string object
let questionAnswer = question.stringByAppendingFormat(answer)

Output
“What time is it? ”
“It is 8:23 am.”
“What time is it? It is 8:23 am.”

String Trimming Methods

String trimming means dropping one or more characters from either end of a string object. In this section you learn how to use a few Swift trimming methods.

dropLast()
This method drop the last character from a string object.

// Declare and initialize a string object
var message  = " It is raining outside?"

// Remove the ? from the string object
dropLast(message)

Output
” It is raining outside?”
” It is raining outside”

dropFirst()
This method drop the first character from a string object.

// Remove the space at the beginning of the string object
dropFirst(" It is raining outside?")

Output
“It is raining outside?”

stringByTrimmingCharactersInSet 
This method drop white spaces off the beginning and end of a string object.

let message = "  Space! These are the voyages of the starship, Enterprise.  "

// Drop only white spaces from the beginning and end of the string object.
message.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Output
”  Space! These are the voyages of the starship, Enterprise.  ”
“Space! These are the voyages of the starship, Enterprise.”

stringByTrimmingCharactersInSet
The method  drops white spaces and the newline characters from a string object.

let message = "  Space! These are the voyages of the starship, Enterprise.  "

// Drop white space and the new line characters from the string object
message.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

Output
”  Space! These are the voyages of the starship, Enterprise.  ”
“Space!
“These are the voyages of the starship, Enterprise.”

String Checking Method

The Swift Programming Language provide many methods for checking to see if a word or character exists in a string object. This sections show you how to use two of them.

containsString()
This method check to see if a particular word exists in a string object. If it does, the method will return the boolean value true; otherwise, it will return false. The method takes a single parameter-a word or character and it is case-sensitive.

let message: NSString = "Space! These are the voyages of the starship, Enterprise."
message.containsString("voyages")

Output
Space! These are the voyages of the starship, Enterprise.
true

StartWith()
This method check to see if a particular word exists in at the beginning of a string object. If it does, the method will return the boolean value true; otherwise, it will return false. The method takes a single parameter-a word or character and it is case-sensitive.

let message: String = "Space! These are the voyages of the starship, Enterprise."
startsWith(message,"Space")

Output
Space! These are the voyages of the starship, Enterprise.
true

isEmpty()

This method check to see if a string object is empty. If it is, the method return the boolean value true; otherwise it return false.

var question = "Why did the chicken crossed the road?"
question.isEmpty

Output
“Why did the chicken crossed the road?”
false

String Concatenating Methods

Concatenating means joining two or more objects together. The Swift Programming provide two operators for concatenating (joining) string and character objects.

addition operator (+)
The Addition operator is for concatenating string and character objects.

concatenate-string-additionopr

addition assignment operator (+=)
The addition assignment operator is for appending a string or character object at the end of an existing string object.

var textMessage1 = "Judy I will be home late tonight, "
let textMessage2 = "so don't wait up me."

// Append textMessage2 to the end of textMessage1
textMessage1 += textMessage2

// Append a character to a string object
var userName = "April "
userName += "M"

Output
“Judy I will be home late tonight, ”
“so don’t wait up me.”
“Judy I will be home late tonight, so don’t wait up me.”
“April ”
“April M”

String Counting Methods

The Swift Programming Language provide two methods for counting the number of characters in a string object. Each method takes a single parameter-a string object and return an integer value.

utf16Count
This method returns the number of characters in a Swift string object. The utf16Count method is the Swift version of Objective-C’s length method. Further more; the method does not count emojis correctly; so you should use the countElements() method instead.  Code below shows how to use it in a playground file.

// Declare and initialize two string objects
var question = "What color is the sky?"
var answer = "The sky is blue."

// Get the number of characters in the question and answer object
question.utf16Count
answer.utf16Count

Output
“What color is the sky?”
“The sky is blue.”
22
16

countElements()
This method returns the number of characters for any sequence, not just string object. Code example below shows how to use the countElements() method to get the length of a constant object that was initialized with only three emoji values: top hat, dress, and jeans.

count-elements-method

If you were to use the utf16Count method on the emojis object the compiler would have displayed the incorrect number 6 in the Result Bar.

Substring Methods

The Swift Programming Language provide two methods for grabbing characters from an existing string object. These methods take only one one parameter-the index position where to start grabbing from. Characters in a string object are zero-based. This mean the first character index number in a string object is zero, the second character’s index number is 1, and so forth.

substringFromIndex()

This method grab characters from an existing string object. It take only one parameter-the index position where to start grabbing from. Code below shows how to use the substringFromIndex() method to grab the last two words from a string object.

let sentence: NSString = "night watch man"
let result = (sentence.substringFromIndex(6))

Output
“night watch man”
“watch man”

Here is a visual of how the substringFromIndex() method’s invisible index pointer works to move from index 6, grabbing every character until it reaches the last character in the sentence string object.

substringFromIndex-method

substringToIndex()

This method grab characters from an existing string object. It take only one parameter-the index position where to stop grabbing from. Code below shows how to use the substringFromIndex() method to grab the first word in a string object.

let sentence: NSString = "night watch man"
let result = (sentence.substringToIndex(5))

Output
“night watch man”
“night”

Here is a visual of how the substringT0Index() method’s invisible index pointer works to move from index 0, grabbing every character until it reaches index 4 in the sentence string object.

substringToIndex-method

Converting a String Object to an Array

Her’s how to use two Swift methods to convert a string object to an array object.

componentsSeparatedByString()

This method convert words in a string object to an array object. The method use one separator for extracting the string object’s words. As you can see in code line 2 belowe, the space character was used as an extraction separator.

let sentence = "night watch man"
let wordsArray = sentence.componentsSeparatedByString(" ")
dump("The wordsArray contain these elements:")
dump(wordsArray)

Output
“night watch man”
[“night”, “watch”, “man”]
“The wordsArray contain these elements:”
[“night”, “watch”, “man”]

componentsSeparatedByCharacterInSet()

This method convert words in a string object to an array object. The method use two characters as separators for extracting the object’s words.

let sentence = "night watch man 5-4-3-2-1"
sentence.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "- "))

Output
“night watch man 5-4-3-2-1”
[“night”, “watch”, “man”, “5”, “4”, “3”, “2”, “1”]

Changing a String Object’s Case

You can change each letter in a Swift string object from lowercase to uppercase and vis versa. Code below shows how.

let sentence1 = "Girl your hair is on fire!"

// Change the string object to uppercase
sentence1.uppercaseString

var sentence2 = "I AM THE NIGHT WATCH MAN"

// Change the string object to lowercase
sentence2.lowercaseString

Output
“Girl your hair is on fire!”
“GIRL YOUR HAIR IS ON FIRE!”
“I AM THE NIGHT WATCH MAN”
“i am the night watch man”