Swift String LengthGet the length of a string with the endIndex property. Loop over the chars based on indexes.
dot net perls

String length. A string contains 6 characters. In Swift, characters may use varying amounts of memory. So we must access our string through indexes not Ints.

EndIndex, a property on strings, returns the index after the final index in a string. So it is equal to the length of the string in characters.

First example. Here we introduce a constant string with contents "dotnetperls." It has 11 characters. The endIndex property equals the value 11. We print it out.

For We next use a while-loop on the string's characters. We begin at startIndex (this is like zero but a string index).

EndIndex We terminate the loop when the index equals the endIndex. So we continue until the last char index.

Index We use this func to increment the current index through the string. We cannot just increment it like an Int, as it is an index.

Finally We print out the individual characters in the string. We must access a string by an index, not an Int.

Swift program that uses string length, endIndex, for-loop
let name = "dotnetperls" // Get the length of the string. let length = name.endIndex print("Length = \(length)") // Loop over all characters in a string. // ... We start at startIndex. // ... And proceed until the endIndex (the length). var temp = name.startIndex; var i = 0; while (temp != name.endIndex) { print("\(i) = \(name[temp])") temp = name.index(after: temp); i += 1; }
Length = Index(_base: Swift.String.UnicodeScalarView.Index( _position: 11), _countUTF16: 0) 0 = d 1 = o 2 = t 3 = n 4 = e 5 = t 6 = p 7 = e 8 = r 9 = l 10 = s

Count characters. To get the length of a string we can use characters.count. We can test this value against an Int. Here we detect a string with 5 chars.

Swift program that uses characters.count, tests length
let platform = "Apple" // Get length of string. let count = platform.characters.count // See if string is 5 characters long. if count == 5 { print(true) } // Print count. print(count)
true 5

Get char based on length. This example uses the endIndex to access the last char in a string. It calls index() with "before" on endIndex which just reduces the index value by 1 char.

Then It invokes remove() to eliminate the final char. The string "abcd" is now just "abc."

Swift program that removes char based on string length
var value = "abcd" print(value) // The last index is before endIndex. let lastCharIndex = value.index(before: value.endIndex) // Remove last char. value.remove(at: lastCharIndex) print(value)
abcd abc

Loop, reverse order. Sometimes we want to loop over a string's chars in reverse order. Here we use endIndex and call index() with "before" to get the last character's index.

Then We print all chars in reverse order. We continue calling index() until no more may exist, and then we exit the loop.


Swift program that loops over string chars in reverse order
let name = "clovis" // Begin at the last valid index. // ... This is endIndex's predecessor. var index = name.index(before: name.endIndex) while true { print(name[index]) // Reduce index by 1 if still greater than 0. // ... Otherwise break out of loop. if index > name.startIndex { index = name.index(before: index) } else { break } }
s i v o l c

Reduce string length. A string's length cannot be directly modified. But with substring() we can truncate a string. Conceptually this reduces the length.


Swift program that reduces length of string
import Foundation let title = "Divine Comedy" // Get index for the desired length. let desiredLength = title.index(title.startIndex, offsetBy: 6) // Use substring. // ... Reduce length of string and create new substring. let truncated = title.substring(to: desiredLength) print(truncated)

Some comments. Strings in Swift are not like strings in many other computer languages. Each char may have a different size. So we cannot treat all chars the same.

Instead We must access strings with an index. This is an abstraction for accessing string data.

Tip Once we understand that chars and strings must be accessed through indexes (and never Ints), strings are more manageable in Swift.

Although The added complexity of indexes does tend to lead to more complex code to do simple string manipulation.

Measuring string length. All things have lengths: some things are short, and others are long. In Swift, we access endIndex to get length. Index() can get the last char in a string.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.