您的位置:首页 > 移动开发 > Swift

Swift学习笔记(6)——字符串和字符(二)

2017-10-27 18:49 246 查看

1. 访问和修改字符串

(一)字符串索引

(1)String.Index,它对应着字符串中的每一个Character的位置。

(2)startIndex属性:获取一个String的第一个Character的索引。

endIndex属性:获取最后一个Character的后一个位置的索引。

所以,endIndex属性不能作为一个字符串的有效下标。如果String是空串,startIndex和endIndex是相等的。

(3)index(before:)index(after:) 方法,可以立即得到前面或后面的一个索引。

index(_:offsetBy:) 方法来获取对应偏移量的索引。

let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a


(4)使用 characters 属性的 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符。

for index in greeting.characters.indices {
print("\(greeting[index]) ", terminator: "")
}
// 打印输出 "G u t e n   T a g ! "


注:

startIndex 和 endIndex 属性或者 index(before:) 、index(after:) 和 index(_:offsetBy:) 方法也可以使用在 Array、Dictionary 和 Set中。

(二)插入和删除

(1)insert(_:at:) 方法:在一个字符串的指定索引插入一个
4000
字符。

insert(contentsOf:at:) 方法:在一个字符串的指定索引插入一个段字符串。

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome 变量现在等于 "hello!"

welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex))
// welcome 变量现在等于 "hello there!"
// 要插入的字符串为" there",在welcome字符串的最后一位(最后一位的后一位的前一位,即最后一位)前插入。


(2)remove(at:) 方法:在一个字符串的指定索引删除一个字符。

removeSubrange(_:) 方法:在一个字符串的指定索引删除一个子字符串。

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome 现在等于 "hello there"
// 删掉最后一位“!”
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome 现在等于 "hello"
// 删掉从字符串最后的后一位开始数,到其前六位,即“ there”


注:

上面所写的属性与方法也可以使用在 Array、Dictionary 和 Set 中。

2. 比较字符串

Swift 提供了三种方式来比较文本值:字符串字符相等、前缀相等和后缀相等。

(一)字符串/字符相等

(1)字符串/字符可以用等于操作符(==)和不等于操作符(!=)

(2)如果两个字符串(或者两个字符)的可扩展的字形群集是标准相等的,那就认为它们是相等的。即使可扩展的字形群集是有不同的 Unicode 标量构成的,只要它们有同样的语言意义和外观,就认为它们标准相等。但是,如果他们的语言意义不一样,就不相等。例如,英语中的LATIN CAPITAL LETTER A(U+0041,或者A)不等于俄语中的CYRILLIC CAPITAL LETTER A(U+0410,或者A)。

(二)前缀/后缀相等

调用字符串的hasPrefix(:)/hasSuffix(:)方法来检查字符串是否拥有特定前缀/后缀,两个方法均接收一个String类型的参数,并返回一个布尔值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: