Swift 4.0:字符串索引用法 String Indices

2017-12-04  本文已影响0人  帅气胡椒面

字符串String类型的变量中包含一种String.Index类型的变量,用于索引字符串中对应的字符。

startIndex是获取字符创中的第一个字符的索引,endIndex是字符串中最后一个字符的后一个字符的索引。因此,endIndex是字符串索引种的非法下标,超出了字符串的范围。

let greeting = "Guten Tag!"

greeting[greeting.startIndex] // 输出 G

greeting[greeting.endIndex] // 在编译时就会报错

主要函数:

1. index(before:) 输出给定索引的前一个索引

greeting[greeting.index(before:greeting.endIndex)] // 输出 !

2. index(after:) 输出给定索引的后一个索引

greeting[greeting.index(after:greeting.startIndex)] // 输出 u

3. index( _:, offsetBy:)   输出给定索引偏移指定量的索引, 只要不超出string的边界,输入的偏移量可以为负值

let index =greeting.index(greeting.startIndex, offsetBy:7)

greeting[index] // 输出 a

String的indices属性:

通过string的indices属性可以更容易地遍历string中的所有字符

for index in greeting.indices {

    print("\(greeting[index]) ", terminator:"")

}  // 输出 "G u t e n T a g ! "

上一篇 下一篇

猜你喜欢

热点阅读