2.字面量
var s = "hello"//字面量
var s1: String = "hello"
var c: Character = "a"
var s2: String = "狗 "
print(s2)
3.初始化空字符串
var s = ""
var s1 = String()
print(s.isEmpty)
print(s1.isEmpty)
4.字符串的可变性
var s1 = "hello"
var s2 = s1+"world"
print(s2)
var s3 = "test"
s3.insert("t", atIndex: s3.startIndex)
print(s3)
5.字符串是值类型
值类型的赋值是拷贝,引用类型的赋值是地址传递,所有的结构体都是值类型的,所有的class类型的都是引用类型的
var s = "hello"
var s2 = s//copy,s,s2是两个
print(s)
print(s2)
s = "world"
print(s)
print(s2)
//引用类型
class person {
var age: Int!
}
var p1 = person()
p1.age = 20
var p2 = p1//同一个对象,两个名字
print(p1.age)
print(p2.age)
print("--------")
p1.age = 21//改变p1的值,p2的值也会跟着改变
print(p1.age)
print(p2.age)
6.使用字符
var s = "hello"
//var c:Character
for c in s.characters{
print(c)
}
var c: Character = "A"//再swift里面字符也是使用双引号
//用数组定义字符串
let cArray: [Character] = ["h","e","l","l","o"]
var s1 = String(cArray)
print(s1)
7.字符串的链接
var s1 = "hello"
var s2 = "world"
var s3 = s1+s2
print(s3)
s1+=s2
print(s1)
s1.appendContentsOf(s2)
print(s1)
var c: Character = "a"
s1.append(c)
print(s1)
8.字符串插值
var name = "tom"
var age = 20
var email = "[email protected]"
var msg = "\(name),\(age),\(email)"
print(msg)
9.转义字符
\0(空字符),\\(反斜杠),\t(水平制表符),\n(换行)
10.字符串的计数
var s = "hello world"
print(s.characters.count)
11.访问和修改字符串
var s = "hello world"
print(s.startIndex)//起始位置
print(s.endIndex)// 结尾位置
print(s.startIndex.successor())//后面的
print(s.endIndex.predecessor())//前面的
print(s.startIndex.advancedBy(3))//某个索引位置的
遍历字符串
var s = "hello"
for index in s.characters.indices{
print(s[index])
}
12.插入字符
var s = "hello"
var c: Character = "A"
s.insert(c, atIndex: s.endIndex)
print(s)
var s2 = "world"
s.insertContentsOf(s2.characters, at: s.endIndex)
print(s)
var s3 = "tom"
s.insertContentsOf(s3.characters, at: s.endIndex.advancedBy(-3))//如果是startindex,则是3
print(s)
13.删除字符
var s = "hello"
//s.removeAtIndex(s.startIndex.advancedBy(3))
//print(s)//删除某个字符
//删除某个范围的字符
let range = s.startIndex..<s.startIndex.advancedBy(2)
s.removeRange(range)
print(s)
14.比较字符串
var s1 = "section1 basic"
var s2 = "section2 basic"
print(s1==s2)
print(s1 != s2)
print(s1.hasPrefix("section1"))//前缀
print(s2.hasSuffix("basic"))//后缀
15.字符串的unicode表示
var dog = "dog!!"
for code in dog.utf8{
print(code)//8位表示
}
print("---------")
for code in dog.utf16{
print(code)//16位表示
}
print("---------")
for code in dog.unicodeScalars{
print(code)//标量表示
}