Swift版的Cocoa框架中的API有了大范围的修改外,Swift的一些核心库也有了很大的改动。其中字符串类型String在方法API上更加简洁,其中变动较大的是与下标相关的方法,列举如下:
var string = "Hello-Swift"
//获取某个下标后一个下标对应的字符 char="e"
var char = string[string.index(after: startIndex)]
//获取某个下标前一个下标对应的字符 char2 = "t"
var char2 = string[string.index(before: string.endIndex)]
//通过范围获取字符串中的一个子串 Hello
var subString = string[startIndex...string.index(startIndex, offsetBy: 4)]
var subString2 = string[string.index(endIndex, offsetBy: -5)..<endIndex]
//获取某个子串在父串中的范围
var range = string.range(of: "Hello")
//追加字符串操作 此时string = "Hello-Swift! Hello-World"
string.append(" Hello-World")
//在指定位置插入一个字符 此时string = "Hello-Swift!~ Hello-World"
string.insert("~", at: string.index(string.startIndex, offsetBy: 12))
//在指定位置插入一组字符 此时string = "Hello-Swift!~~~~ Hello-World"
string.insert(contentsOf: ["~","~","~"], at: string.index(string.startIndex, offsetBy: 12))
//在指定范围替换一个字符串 此时string = "Hi-Swift!~~~~ Hello-World"
string.replaceSubrange(string.startIndex...string.index(string.startIndex, offsetBy: 4), with: "Hi")
//在指定位置删除一个字符 此时string = "Hi-Swift!~~~~ Hello-Worl"
string.remove(at: string.index(before:string.endIndex))
//删除指定范围的字符 此时string = "Swift!~~~~ Hello-Worl"
string.removeSubrange(string.startIndex...string.index(string.startIndex, offsetBy: 2))
var string2 = "My name is Jaki"
//全部转换为大写
string2 = string2.uppercased()
//全部转换为小写
string2 = string2.lowercased()