String Indices

Each String has an associated index type, string.index, which records the position of each character in the String. An integer subscript cannot be used to index characters, because each character in a string occupies different memory space. Therefore, each character must be iterated through the head or tail of the string to determine the position of each character.

Index Getter

// Position of the first character
@inlinable public var startIndex: String.Index { get }
// The position after the last character, the empty string startIndex==endIndex
@inlinable public var endIndex: String.Index { get }
Copy the code

Access Index

func index(after i: String.Index) -> String.Index
func index(before i: String.Index) -> String.Index
func index(_ i: String.Index.offsetBy n: String.IndexDistance) -> String.Index
Copy the code

Example

var str = "Hello, String"
print(str.startIndex) // Index(_rawBits: 1)
print(str.endIndex)   // Index(_rawBits: 851969)
print(str.count)      / / 13
Copy the code

Inserting and Removing

Example

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)  // "hello!"
// "hello String!"
welcome.insert(contentsOf: " String", at: welcome.index(before: welcome.endIndex)) 
// return "!" , welcom="hello String"
welcome.remove(at: welcome.index(before: welcome.endIndex))

let range = welcome.index(welcome.endIndex, offsetBy: -7) ..< welcome.endIndex 
welcome.removeSubrange(range) // "hello"
Copy the code

Substrings

Substring generation and memory optimization

Intercepting a String generates an instance of Substring, and most operations on Substring and String are the same. Substrings can be used for short periods of time; if you want to store results for long periods of time, you need to convert subStrings to Strings

  • Substring reuses part of the memory of the original string (string has the same optimization, two strings share memory, then two strings are equal).
  • This means that a string or substring of shared memory is copied in memory only if it is modified
  • To sum up, a substring is not suitable for long-term storage because it uses the memory of the original string. As long as the substring is in use, the entire original string must be kept in memory, as shown in the figure below.
  • Both String and Substring complyStringProtocolProtocol, so you can easily get one using the string methodStringProtocolvalue

Example

var greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex

let beginning = greeting[..<index]
let newString = String(beginning) // Convert the result to a String for long-term storage.

greeting.remove(at: greeting.startIndex)

print(greeting, beginning, newString)

result: ello, world! Hello Hello
Copy the code

Reference

Swift Document – Strings and Characters