Swift - Data Type Substrings

Introduction

First, consider the following swift String:

let swiftString:String = "The quick brown fox jumps over the lazy dog."

Every String type has a number of properties of type String.Index.

Index is a structure that contains a number of properties that point to the current character in the String variable, its next character, its previous character, and so on.

Consider the following statement:

print(swiftString[swiftString.startIndex ])  //T

Here, startIndex property of type String.Index to refer to the first character of the string.

You use it as the index to pass to the String's subscript() method to extract the first character.

You cannot directly specify a number indicating the position of the character that you want to extract, like this:

print(swiftString[ 0 ])  //error

You can use the endIndex property together with the predecessor() method to get the last character in the string:

print(swiftString [swiftString.endIndex.predecessor()]) //.

To get the character at a particular index, you can use the advance() method and specify the number of characters to move relative to a starting position:

Demo

let swiftString:String = "The quick brown fox jumps over the lazy dog."
//start from the string's startIndex and advance 2 characters
var index = advance(swiftString.startIndex, 2)
print(swiftString [index])   //e

Here, index is of type String.Index. You use it to extract the character from the string.

You can traverse the string backwards by starting at the end index and specifying a negative value to move:

Demo

let swiftString:String = "The quick brown fox jumps over the lazy dog."
var index = advance(swiftString.endIndex, -3)
print(swiftString[index])  //o

The successor() method returns the position of the character after the current character:

print(swiftString[index.successor()])    //g

The predecessor() method returns the position of the character prior to the current character:

print(swiftString [index.predecessor()])  //d

You can use the subStringFromIndex() method to obtain a substring starting from the specified index:

print(swiftString.substringFromIndex(index))
//e quick brown fox jumps over the lazy dog.

To get the substring from the beginning up to the specified index, use the substringToIndex() method:

print(swiftString.substringToIndex(index))  //Th

Related Topic