Swift中String和Character的使用与总结

Blog UV: AmazingCounters.com


使用String字面量给常量赋值

let string = "string literal value"  

常量string将会自动推断为String类型


初始化一个空的String

var emptyStr = ""              //使用空字符串字面量  
var anotherEmptyStr = String() //使用构造方法  
//两者没有区别

使用isEmpty判断空String:

if emptyStr.isEmpty {  
    print("have nothing here")
}


String的可变性

使用“+”连接字符串,当然也支持自加运算符"+="

var variableStr = "LastName"  
variableStr += "and FirstName"  
/// variableStr is "LastName and FirstName"

//**but if:
let constantStr = "Gender"  
constantStr += "and another Highlander"  
///编译器会报错,被声明为常量的字符串不能被修改!

跟oc不同,swift的String通过var/let 变量/常量 标识决定其是否可变(can be mutated),而不需要选择NSString 还是 NSMutableString。


String是值类型

区别引用类型,在String在方法间传递,或者将其赋值给一个常量或者变量时,该String将会被复制(copy),而不是指向原来的对象。


String跟Characters的连接

let str = "hello world "  
let char: Character = "!"  
str.append(char)  
// 结果str为: "hello world !"


遍历String

for char in "myStr".characters {  
    print(char)
}
//m
//y
//S
//t
//r


字符串插值

在字符串中插入常量变量表达式等,构造一个新的字符串"通过()":

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来进行特殊符号表情的显示:

//**双引号转义
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"  
///"Imagination is more important than knowledge" - Einstein

//**Unicode转义
let dollarSign = "\u{24}"        // $,  Unicode scalar U+0024  
let blackHeart = "\u{2665}"      // ♥,  Unicode scalar U+2665  
let sparklingHeart = "\u{1F496}" // ��, Unicode scalar U+1F496

//**扩展自行集
//**对应关系
//  \u{D55C}----한
//  \u{1112}----á„’
//  \u{1161}----á…¡
//  \u{11AB}----ᆫ
let KoreaStr = "\u{D55C}\u{1112}\u{1161}\u{11AB}" //한한  


String长度

string.characters.count

let str = "1234567890"  
print("str has \(str.characters.count) characters")  
//输出 "star has 10 characters"

//**为String增加笔画不会造成长度增加:
var str = "cafe"  
print("the number of characters in \(word) is \(word.characters.count)")  
// 输出 "the number of characters in cafe is 4"
//**now append some Unicode:
word += "\u{301}"  
print("the number of characters in \(word) is \(word.characters.count)")  
//输出 "the number of characters in café is 4"
//仅仅是改变了最后一个字符,并没有增加字符串的长度

正因为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) )

let greeting = "Guten Tag!"  
greeting[greeting.startIndex]  
//G
greeting[greeting.endIndex.predecessor()]  
//!
greeting[greeting.startIndex.successor()]  
//u
let index = greeting.startIndex.advancedBy(7)  
//a
greeting[index]  
//输出 a

indiced : 字符串Index的集合

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


插入/移除

利用index,在制定位置插入字符character

var helloStr = "hello"  
helloStr.insert("~", atIndex: helloStr.endIndex)  
// hello~

同理,插入字符串(字符的集合)

var helloStr = "hello!"  
helloStr.insertContentOf(" world!".characters, at: hello.endIndex)  
// hello! world

//用上面的知识,再追求下完美:
var helloStr = "hello!"  
helloStr.insertContentOf(" world".characters, at: hello.endIndex.predecessor())  
// hello world!

移除(index):

var helloStr = "hello world!"  
helloStr.removeAtIndex(helloStr.endIndex.predecessor())  
// hello world
//注意:
// endIndex是指最后一个index位(将要输入内容的index位)
//所以删除最后一个字符使用的index是endIndex.predecessor()(将要输入内容的index的前一个index位)
//而不是endIndex

移除(Range):

var helloStr = "hello world!"  
let range = Range(start: helloStr.endIndex.advancedBy(-6), end: helloStr.endIndex.predecessor())  
// 顺便贴一个new Range的简易写法:
// let range = helloStr.endIndex.advancedBy(-6)..<helloStr.endIndex
// 效果是一样的
helloStr.removeRange(range)  
// hello


字符串比较

两个纯字符串比较

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")
}
//输出: These two strings are considered equal
//相等

两个由characters组成的字符串比较

let oneStr = "Voulez-vous un caf\u{E9}?"  
//Voulez-vous un café?
let anotherStr = "Voulez-vous un caf\u{65}\u{301}?"  
//Voulez-vous un café?
//两者虽然看起来内容字符不同,其实\u{65}\u{301}是一个e和一个音调符号,根据上面的知识,结果组合成é(\u{E9})

if oneStr == anotherStr {  
    print("These two strings are considered equal")
}
//输出: These two strings are considered equal
//相等

两个表现相同的character比较

let oneChar: Character = "\u{41}"  
//拉丁字母中的A
let anotherChar: Character = "\u{0410}"  
//西里尔字母中的A

if oneChar != anotherChar {  
    print(These two characters are not equivalent)
}
//输出: These two characters are not equivalent
//不相等!

前缀和后缀的比较 我们可以使用hasPrefix()方法和hasSuffix()去匹配String的前缀和后缀,并返回一个Boolean值

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 ")  
// 输出: "There are 5 string with Act 1"

//----后缀呢
var count = 0  
for str in romeoAndJuliet {  
    if str.hasSuffix("Capulet's mansion") {
        count++
    } 
}
print("There are \(count) mansion string")  
// 输出: "There are 6 mansion stressing"


String使用UTF-8编码表示

复习一下,上面也提到,Swift中的String支持emoji表情和众多特殊字符,这也是String一个单位长度不一定等于两个character(汉字)或者1个character(英文字母)的原因。 先回到我们的话题。String和UTF-8的对应关系,我们来看一张官方电子书中的表: ![]/content/images/2015/12/utf8.png()

//上图中对应的String:
//let dogString = "Dog!!��"

//同时String中的UTF-8编码也是可以像char那样遍历的
for unitCode in dogString.utf8 {  
    print("\(unitCode) ", terminator: "")
}
//输出: 68 111 103 226 128 188 240 159 144 182

同理String也可以以UTF-16 和Unicode的方式遍历

for unitCode in dogString.utf16 {  
}

for scalar in dogString.unicodeScalars {  
    print("\(scalar.value) ", terminator: "")
}
// 68 111 103 8252 128054

for scalar in dogString.unicodeScalars {  
    print("\(scalar) ", terminator: "")
}
// D o g !! ��

//注意: 直接printunicodeScalar的话跟String的输出是一样效果的
//我们print出他的value,才是我们想要的编码
comments powered by Disqus