1.3 Strings

Character

  • a single character
  • not inferred → must explicitly force the type

String

  • multiple characters
  • the default for letters

Declaration

// declaration - create but don't initialize<br>
var myString1: String

// declaration - create/init with 0 value
var myString2 = String()

// create and initialize with an initial value (preferred)
var myChar: Character = "!"
var myString3 = "Hello"

// create multiple variables
var animal = "bear", bird = "crane"

Concatenation and Interpolation +

var greeting = "Hello, "<br>
var cat = "Whiskers meow meow"

// concatenation
print(greeting + cat + ".")

// concatenation with char
cat.append(myChar)

// interpolation
print("My cat's name is \(cat)")

// add & assign to existing string
greeting += cat
  • interpolation can also embed expressions

Multi-Line

  • strings can span multiple lines without quotes on each line
let longString = """<br>
When you write a string that spans multiple<br>
lines make sure you start its content on a<br>
line all of its own, and end it with three<br>
quotes also on a line of their own.<br>
Multi-line strings also let you write "quote marks"<br>
freely inside your strings, which is great!<br>
"""

Iterating and Reversing

  • strings are a collection of characters
  • each string has an index type which corresponds to the position of chars
// iterating thru each character of name -> F i d o<br>
let dogName = "Fido"<br>
for dogChars in dogName {<br>
   print(dogChars)<br>
}

// reversing -> odiF
let reversed = String(dogName.reversed())

Formatting Decimals w/ String

let angle = 45.6789<br>
let formatted = String(format: "Angle: %.2f", angle)
  • %F → a floating point number
  • .2 → 2 digits after the decimal

Search

// search w/in a string<br>
var bookTitle = "  War and Peace  "

// -> false (case sensitive)
if bookTitle.range(of: "war") != nil {
   print("war appears in the title")
}

// -> true (case insensitive)
if bookTitle.range(of: "peace", options: .caseInsensitive) != nil {
   print("peace appears in the title")
}

// identify suffix -> true
if bookTitle.hasPrefix("War") {
   print("War first")
}

// identify prefix -> true
if bookTitle.hasSuffix("Peace") {
   print("Peace at end")
}

Search and Replace

// search and replace -> WarandPeace<br>
bookTitle.replacingOccurrences(of: " ", with: "")

// for just beg/end use -> War and Peace
let trimmed = bookTitle.trimmingCharacters(in: .whitespacesAndNewlines)
print(trimmed)

Separating Strings based on Components

// -> array: "War", "and", "Peace"<br>
var titleBreakdown = trimmedTitle.components(separatedBy: " ")<br>
print(titleBreakdown)

Selection

// select characters<br>
let newSubString = NSString(string: "War and Peace")

// -> War
newSubString.substring(to: 3)

// -> ace
newSubString.substring(from: 10)

// selecting a range -> "and"
newSubString.substring(with: NSRange(location: 4, length: 3))

// combined conversion and selection -> "and"
NSString(string: newSubString.substring(from: 4)).substring(to: 3)
  • must convert to NSString to use these functions

Other Methods

let mouseName = "Mickey"

// counting characters -> 6 characters
var nameNum = (mouseName.count)

// confirm contents
if mouseName.isEmpty {
   print("no mouse in here")
}

// change case
mouseName.uppercased()
mouseName.lowercased()

// capitalize each char before a space
mouseName.capitalized