使用String字面量给常量赋值
1 2
| let string = "string literal value" //常量string将会自动推断为String类型
|
初始化一个空的String
1 2 3
| var emptyStr = "" var anotherEmptyStr = String()
|
使用isEmpty判断空String:
1 2 3
| if emptyStr.isEmpty { print("have nothing here") }
|
String的可变性
使用“+”连接字符串,当然也支持自加运算符”+=”
1 2 3 4 5 6 7 8
| var variableStr = "LastName" variableStr += "and FirstName" let constantStr = "Gender" constantStr += "and another Highlander"
|
跟oc不同,swift的String通过var/let 变量/常量 标识决定其是否可变(can be mutated),而不需要选择NSString 还是 NSMutableString。
String跟Characters的连接
1 2 3 4 5
| let str = "hello world " let char: Character = "!" str.append(char)
|
遍历String
1 2 3 4 5 6 7 8
| for char in "myStr".characters { print(char) }
|
字符串插值
在字符串中插入常量变量表达式等,构造一个新的字符串”通过()”:
1 2 3
| let multiplier = 3 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" /// message is "3 times 2.5 is 7.5"
|
String中使用转义字符
在字符串中输入反斜线”\” 水平制表符”t” 换行”n” 双引号”“” 单引号”’” 等都需要在前面添加”\”进行转义,同时可以在转义字符后添加Unicode来进行特殊符号表情的显示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let wiseWords = "\"Imagination is more important than knowledge\" - Einstein" let dollarSign = "\u{24}" let blackHeart = "\u{2665}" let sparklingHeart = "\u{1F496}" let KoreaStr = "\u{D55C}\u{1112}\u{1161}\u{11AB}"
|
String长度
string.characters.count
1 2 3 4 5 6 7 8 9 10 11 12 13
| let str = "1234567890" print("str has \(str.characters.count) characters") var str = "cafe" print("the number of characters in \(word) is \(word.characters.count)") word += "\u{301}" print("the number of characters in \(word) is \(word.characters.count)")
|
正因为swift支持扩展字形集,不同的字符,和相同的不同表示的字符可能需要不同量的存储器来存储,所以在swift中characters所占用的存储量是不一定相同的,因此不能像oc计算NSString那样使用字符串来迭代计算,而应该遍历字符串的characters来确定字符串的长度。
####访问和修改字符串
可以通过其方法和属性,或者下标,来访问或者修改字符串
###字符串索引
swift中的字符串具有相关连的索引类型(String.Index),可对应其每个位置的Character
正如上面所说,不同的字符串可能需要不同数量的内存来存储,所以为了确定哪些character在特定的位置上,我们必须遍历确定每个Unicode的开始结束位置,因此,String不能使用整形作索引。
startIndex: 访问String第一个位置的字符 endIndex: 访问String最后一个位置的字符
(一个空的字符串或者长度为1的字符串,startIndex和endIndex相等)
predecessor(), successor(), advancedBy() 一个String.Index值可以通过调用predecessor()方法来访问其前一个index, 调用successor()来访问其后一个index, 或者调用advancedBy()来指定访问相对位置的index( 之后5位的index: advancedBy(5) 往前5位的index: advancedBy(-5) )
1 2 3 4 5 6 7 8 9 10 11
| let greeting = "Guten Tag!" greeting[greeting.startIndex] greeting[greeting.endIndex.predecessor()] greeting[greeting.startIndex.successor()] let index = greeting.startIndex.advancedBy(7) greeting[index]
|
indiced : 字符串Index的集合
1 2 3 4
| for index in greeting.characters.indices { print("\(greeting[index])", terminator: " ") }
|
插入/移除
利用index,在制定位置插入字符character
1 2 3
| var helloStr = "hello" helloStr.insert("~", atIndex: helloStr.endIndex)
|
同理,插入字符串(字符的集合)
1 2 3 4 5 6 7 8
| var helloStr = "hello!" helloStr.insertContentOf(" world!".characters, at: hello.endIndex) var helloStr = "hello!" helloStr.insertContentOf(" world".characters, at: hello.endIndex.predecessor())
|
移除(index):
1 2 3 4 5 6 7
| var helloStr = "hello world!" helloStr.removeAtIndex(helloStr.endIndex.predecessor())
|
移除(Range):
1 2 3 4 5 6 7
| var helloStr = "hello world!" let range = Range(start: helloStr.endIndex.advancedBy(-6), end: helloStr.endIndex.predecessor()) helloStr.removeRange(range)
|
####字符串比较
两个纯字符串比较
1 2 3 4 5 6 7 8
| let oneStr = "We're a lot alike, you and I." let anotherStr = "We're a lot alike, you and I." if oneStr == anotherStr { print("These two strings are considered equal") }
|
两个由characters组成的字符串比较
1 2 3 4 5 6 7 8 9 10 11
| let oneStr = "Voulez-vous un caf\u{E9}?" let anotherStr = "Voulez-vous un caf\u{65}\u{301}?" if oneStr == anotherStr { print("These two strings are considered equal") }
|
两个表现相同的character比较
1 2 3 4 5 6 7 8 9 10
| let oneChar: Character = "\u{41}" let anotherChar: Character = "\u{0410}" if oneChar != anotherChar { print(These two characters are not equivalent) }
|
前缀和后缀的比较 我们可以使用hasPrefix()方法和hasSuffix()去匹配String的前缀和后缀,并返回一个Boolean值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| 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" ] var count = 0 for str in romeoAndJuliet { if str.hasPrefix("Act 1 ") { count++ } } print("There are \(count) string with Act 1 ") var count = 0 for str in romeoAndJuliet { if str.hasSuffix("Capulet's mansion") { count++ } } print("There are \(count) mansion string")
|
String使用UTF-8编码表示
复习一下,上面也提到,Swift中的String支持emoji表情和众多特殊字符,这也是String一个单位长度不一定等于两个character(汉字)或者1个character(英文字母)的原因。 先回到我们的话题。String和UTF-8的对应关系,我们来看一张官方电子书中的表: ![]/content/images/2015/12/utf8.png()
1 2 3 4 5 6 7 8
| for unitCode in dogString.utf8 { print("\(unitCode) ", terminator: "") }
|
同理String也可以以UTF-16 和Unicode的方式遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| for unitCode in dogString.utf16 { } for scalar in dogString.unicodeScalars { print("\(scalar.value) ", terminator: "") } for scalar in dogString.unicodeScalars { print("\(scalar) ", terminator: "") }
|
copy 自:
http://zyden.vicp.cc/string-character/