String
Strings in Swift are collections of characters, but they can be complicated to use. We cannot access characters just by integers. This allows strings to support a wide range of characters.
In this language, a for
-loop allows us to access each individual character. We can test or count or these characters. The count property is often useful.
Let us begin with a simple for
-loop. The "c" variable here is the current iteration's character. We call print()
on the characters.
string
, we can access the count property. To count specific chars, we use for
-loop with if
-statements.for-in
loop, we cannot access adjacent characters in a string
. We must use an index loop for this.let value = "cat" // Loop over characters in string. for c in value { print(c) }c a t
Count
This property returns the number of characters in the string. So with the string
"carrot" it will return 6. The property cannot be assigned.
var vegetable = "carrot" // Get count of chars in string. let c = vegetable.count print(c)6
Contains
This method receives a Character, which can be specified as a one-char string
. It returns true if the Character exists in the string, and false otherwise.
var vegetable = "turnip" // The string contains this letter. let n = vegetable.contains("n") print(n) // There is no "x" in the string. let x = vegetable.contains("x") print(x)true false
Count
charsTo get the number of characters in a string
, we can use count. All characters, including spaces and punctuation, are counted by this property.
endIndex
property. This is an index so it can be used to access and manipulate other parts of the string
data.// This string has four characters in it. var value = "bird" var length = value.count print(length) // This string has six characters. // ... Spaces and other chars are all counted. value = "x y z " length = value.count print(length)4 6
IsEmpty
It is possible to test for an empty (zero-length) string
by using the isEmpty
property. This returns true if the count is zero.
// Demonstrate empty string. let color = ""; if color.isEmpty { print("IS EMPTY"); }IS EMPTY
String
A string
may be created from a Character array. Here we create a Character array of six characters. When we convert it to a string
, it equals the name "Sancho."
// Create a character array. let chars: [Character] = ["S", "a", "n", "c", "h", "o"] // Create a string from the character array. let result = String(chars) print(result) // Test the string value. if result == "Sancho" { print(true) }Sancho true
We can apply UnicodeScalar
to convert Ints into Characters. And with utf8 and utf16 we can access integral values in a string
's character data.
We can directly access characters in a string
. We can use this in a for
-loop to test a string
's text data. Other properties like count can also be useful.