Swift Basics - Strings

Using strings:

Declaring a multiple line string variable:
var multiLineString = """
ABCD
EFGHI
"""
You can add quotes in multiple line variables:
var heSaid = """
He said,"Hello."
"""

To go through each character in a string:
for char in nameOfString.characters
{
 print(char)
}  
OR
nameOfString.map
{
 print($0)
}

Concatenate 2 strings:
var c = a + b
a += b
b = "Hello \(a)"
You cannot add another part of a string to a constant.

Print in lowercase:
a.lowercased()
b.uppercased()
Replace an occurrence of a string with another:
nameOfString.replacingOccurences(of: "boy", with: "girl")

Working with substrings
Getting a string between the third and eighth character of a string:
let starting = nameOfString.index(nameOfString.startIndex, offsetBy: 2)
let ending = nameOfString.index(nameOfString.startIndex, offsetBy: 7)
let theSubString = nameOfString[starting ..< ending]
let newString = String(theSubString)

If you have a string and you wish to get the first 3 characters:
nameOfString.substring(to: starting)
You wish to extract out the last 4 characters:
nameOfString.substring(from: ending)

Getting the first letter of the string:
nameOfString.first
Getting the last letter of the string:
nameOfString.last
Getting the number of letters in a string:
var length = nameOfString.count



Comments

Popular posts from this blog

Setting up a playground

Go to another page