Skip to content

Latest commit

 

History

History
265 lines (185 loc) · 4.24 KB

File metadata and controls

265 lines (185 loc) · 4.24 KB

Basics | Arrays | Colors | Date and Time | Dictionaries | Sets | Sorting | Strings | Functional Swift

Swift Strings

String Creation

var mystr:String // Mutable string

mystr = "\n"   // a newline character
let s1 = "\\n" // Two characters, \ and n
let bear = "🐻"

mystr = "Jon \"Maddog\" Orwant"  // escaped double quote
var str = "Hello, playground" // Mutable string
let language = "Swift" // Immutable string


var str1: String
var str2: String = "hello world"

String Length

let stringLength = str.count

String Equality

if str == "Hello, playground" {
    print("Strings are Equal")
}

Case Insensitive Comparison

let nativeLanguage = "French"
if nativeLanguage.caseInsensitiveCompare("french") == .orderedSame { // NSComparisonResult.OrderedSame
    print("Strings are equal")
}

String Inequality

if str != "Hello world" {
    print("Strings are NOT Equal")
}

Test for Empty String

var aString = ""
if aString.isEmpty {
    print("String is empty")
}

Concatenate

str1 = "Hello, "
str2 = "playground"

str = str1 + str2 // Swift's concatenate operation
str = "\(str1)\(str2)" // Using String interpolation

Append string

str = "hello"
str += " world"

Append a single character

let period: Character = "."
str.append(period)

Prepend string

_ = "My \(str)" // Ignoring result
_ = "My " + str

Remove Last Character/chop

var s = "abcd"
let lastChar: Character = s.removeLast() // mutates s == "abc"

Simple CSV split

let csv = "one,two,3"

let anArray = csv.components(separatedBy: ",")
print(anArray)

Join string to CSV

anArray.joined(separator: ",")
//: String Contains a Substring

str = "www"
let url = "https://www.h4labs.com/"

if url.contains(str) {
    print("Contains string: \(str)")
}

Replace/Remove All Characters in String

let row = "id first last"
let csv = row.replacingOccurrences(of: " ", with: ",") // import Foundation
let noSpaces = row.replacingOccurrences(of: " ", with: "") 

var s = "<html>## header"
s.removeAll(where: ["<", ">"].contains) // mutate s - Set<Character>

String begins with/Has prefix

url.hasPrefix("https:")

String ends with/Has suffix

url.hasSuffix("/")

String to Letter Array/Split string by character

var letters:[String] = []
"horse".forEach {letters.append(String($0))}
letters
let arr = str.map { String($0) }

Trim White Space

var blogTitle = "  Swift Cookbook  ".trimmingCharacters(in: NSCharacterSet.whitespaces)

//stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Trim White Space and Remove Newlines

blogTitle = "  Swift Cookbook  \n".trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
//: Remove surrounding quotes
let quotedString = "\"h4labs\""

let quotesRemoved = quotedString.replacingOccurrences(of: "\"", with: "")

Uppercase string

var company = "apple computer"
company = company.uppercased()

Capitalize/Title case

company = company.capitalized// capitalize every word
company = company.localizedCapitalized // capitalize every word localized

Lowercase

company = company.lowercased()

Loop Over Every Character of String

for character in "hello world" {
    print(character)
}
let letters = "abcdefg"
var csv = ""
for character in letters {
    csv.append(character)
    csv.append(",")
}
print(csv)

String to Int

let aNumberStr = "10"
let anInt: Int? = Int(aNumberStr)
let i: Int = Int(aNumberStr) ?? 0 // default to zero and make nonnullable

String to Double

let aDouble: Double? = Double(aNumberStr)

First letter

let aWord = "hello"
let firstLetter = aWord.first
let lastLetter = aWord.last
let x = aWord.prefix(3)
String(x)

Multi-line Strings

let str = """
.#..#
 .....
 #####
 ....#
 ...##
"""

TODO

Is a String a Digit/isDigit