哈哈哈,刚才看见微博,有人推荐一个神奇的工具,推荐给大家http://swiftlang.ng.bluemix.net/#/repl是IBM公司出的,编译器的版本是Swift2.2,现在可以使用之前的String的那些方法了,哈哈哈
插入和删除(Inserting and Removing)
调用insert(_:atIndex:)方法可以在一个字符串的指定索引插入一个字符
var welcome = "hello"
welcome.insert("!",atIndex:welcome.endIndex)
//welcome现在就是"hello!"
还可以在一个字符串的指定索引插入一个字符串,调用insertContentsOf(_:at:)方法
welcome.insertContentsOf(" there".characters, at: welcome.endIndex.predecessor())
现在welcome就是"hello there!"(是接着上面的例子哦,暂时的编译器还是会报错的,待升级之后再试试)
调用removeAtIndex(_:) 方法可以在一个字符串的指定索引删除一个字符
var welcome = "hello there!"
welcome.removeAtIndex(welcome.endIndex.predecessor())
//这时候welcome的值就是"hello there",把最后一个字符后一位的前一位移除了就是移除了"!"
调用removeRange(_:)方法可以在一个字符串指定索引删除一个子字符串
var welcome = "hello there"
let range = welcome.endIndex.advanceBy(-6)..
DAY2里面说过,我们可以调用advanceBy()来获取一个索引,编译器的原因暂时不能实现,上面的例子表示的意思是从空格删除到最后的e,welcome现在就等于hello
比较字符串(Comparing Strings)
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
print("These two string are considered equal")
}
//These two string are considered equal
我们可以使用(==)和(!=)来比较,如果两个字符串的可扩展的字形群集是标准相等的,那么它们就是相等的,即使可扩展的字形群集是由不同的Unicode标量构成的,只要语言意义和外观相同就认为是相同的.
let a = "caf\u{E9}" //é
let b = "caf\u{65}\u{301}" //e和重音符号
if a == b{
print("These two strings are considered equal")
}
//These two strings are considered equal
前缀/后缀相等(Prefix and Suffix Equality )
通过调用字符串hasPrefix()/hasSuffix()方法来检查是否有前后缀,两个都输入一个String类型的参数,返回一个布尔值。这里举了一个例子,用一个定义为常量的数组romeoAndJuliet,可以看见,数组是用[]来申明的,数组内的变量用逗号隔开,具体的数据类型我看后面有详细的章节会讲,到时候学习
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
定义了一个变量用来计数前缀中含有Act 1的,这里一共有五次
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1"){
++act1SceneCount
}
}
print("There are \(act1SceneCount) scenes in Act 1")
//There are 5 scenes in Act 1
定义了两个变量,来数字符串后缀中含有这两个的值,这里有一个for循环一个if,else if循环,具体的语法后面也有详细的章节讲解
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet{
if scene.hasSuffix("Capulet's mansion"){
++mansionCount
}else if scene.hasSuffix("Friar Lawrence's cell"){
++cellCount
}
}
print("\(mansionCount) mansion scenes;\(cellCount) cell scenes")
//6 mansion scenes;2 cell scenes
Unicode Representations of Strings
apple的String&Character中还有这个章节Unicode Representations of Strings,这里就不示范了,有兴趣的大家可以看一下,我睡觉前看下~