Characters and Strings in Swift, A string is a series of characters, such as “hello, world”. Swift strings are represented by the String type.
The contents of a String can be accessed in various ways, including as a collection of Character values.
The syntax for string creation and manipulation is lightweight and readable, with a string literal syntax that’s similar to C
String Instance
We can also create a string using an initializer syntax.
var str = String()
String Literals
A string literal is a sequence of characters surrounded by double quotation marks (“).
let someString = “Some string”
Multiline String Literals
If you need a string that spans several lines, use a multiline string literal—a sequence of characters surrounded by three double quotation marks
// multiline string
var str: String = """
Swift is awesome
I love Swift
"""
Special Characters in String Literals
String literals can include the following special characters:
The escaped special characters
\0 (null character),
\\ (backslash),
\t (horizontal tab),
\n (line feed),
\r (carriage return),
\" (double quotation mark)
\' (single quotation mark)
Swift Character
Character is a data type that represents a single-character string (“a”, “@”, “5”, etc).
We use the Character keyword to create character-type variables in Swift.
// create character variable
var letter: Character = "H"
print(letter) // H
Swift String
In Swift, a string is used to store textual data (“Swift is awesome.”).
We use the String keyword to create string-type variables.
let name: String = "Swift"
print(name)
Compare Two Strings
We use the == operator to compare two strings. If two strings are equal, the operator returns true.
let str1 = "Hello, world!"
let str2 = "I love Swift."
// compare str1 and str2
print(str1 == str2)
Join Two Strings
We use the append() function to join two strings in Swift.
var greet = "Hello "
var name = "Mycodetips"
// using the append() method
greet.append(name)
print(greet)
Concatenate String
We can also use the + and += operators to concatenate two strings.
var greet = "Hello, "
let name = "Mycodetips"
// using + operator
var result = greet + name
print(result)
//using =+ operator
greet += name
print(greet)
Find Length of String
We use the count property to find the length of a string.
let message = "Hello, World!"
// count length of a string
print(message.count) // 13
Escape Sequences
The escape sequence is used to escape some of the characters present inside a string.
// use the escape character
var example = "This is \"String\" class"
print(example)
String Interpolation
String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash ()
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
Counting Characters
To retrieve a count of the Character values in a string, use the count property of the string
let unusualMenagerie = "Koala, Snail, Penguin, Dromedary"
print("unusualMenagerie has \(unusualMenagerie.count) characters")
// Prints "unusualMenagerie has 40 characters"
var word = "cafe"
print("the number of characters in \(word) is \(word.count)")
// Prints "the number of characters in cafe is 4"
String Indices
Each String value has an associated index type, String.Index, which corresponds to the position of each Character in the string.
Inserting and Removing
To insert a single character into a string at a specified index, use the insert(_:at:) method, and to insert the contents of another string at a specified index, use the insert(contentsOf:at:) method.
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
Substrings
Characters and Strings,When you get a substring from a string—for example, using a subscript or a method like prefix(_:)—the result is an instance of Substring, not another string. Substrings in Swift have most of the same methods as strings, which means you can work with substrings the same way you work with strings.
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"
Prefix and Suffix Equality
To check whether a string has a particular string prefix or suffix, call the string’s hasPrefix(🙂 and hasSuffix(🙂 methods, both of which take a single argument of type String and return a Boolean value.
You can use the hasPrefix(_:) method with the romeoAndJuliet array to count the number of scenes in Act 1 of the play
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
act1SceneCount += 1
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// Prints "There are 5 scenes in Act 1"
Similarly, use the hasSuffix(_:) method to count the number of scenes that take place in or around Capulet’s mansion and Friar Lawrence’s cell:
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
mansionCount += 1
} else if scene.hasSuffix("Friar Lawrence's cell") {
cellCount += 1
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// P
Unicode Representations of Strings
When a Unicode string is written to a text file or some other storage, the Unicode scalars in that string are encoded in one of several Unicode-defined encoding forms.
UTF-8 Representation
You can access a UTF-8 representation of a String by iterating over its utf8 property. This property is of type String.
UTF-16 Representation
You can access a UTF-16 representation of a String by iterating over its utf16 property. This property is of type String.
Unicode Scalar Representation
You can access a Unicode scalar representation of a String value by iterating over its unicodeScalars property. This property is of type UnicodeScalarView, which is a collection of values of type UnicodeScalar.
Happy Coding using Characters and Strings:)
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.