初始化字符串
let str1:String="Hello"
let str2 = "world"
字符串的拼接
var str = str1 + " beautiful " + str2 // Hello beautiful world
获取字符串长度,判断字符串是否为空
let str = String(format: "Hello world %@", "welcome!")
str.count //20
str.isEmpty // false
let str1 = ""
str1.isEmpty // true
str1.count //0
字符串格式化
let str = "hello world"
let str1 = String(format:"学习%@",str)//"学习hello world
let str2 = String(format:"第%d天",1)//第1天
let str3 = String(format:"瘦了%.2fkg",0.123)//瘦了0.12kg
let str4 = String(3.14)// 3.14
字符串的遍历
let str = "3.14"
for i in str {
print(i)
//3
//.
//1
//4
}
字符串的增、删、改、查
1、增
var str = "hello"
str.append("World") //helloWorld
2、删
var str = "hello"
//删首尾字符
str.removeFirst()
str.removeLast()
str //elloWorl
//删指定位置
str.remove(at:str.index(str.startIndex, offsetBy:3))
str //ellWorl
//删所有
str.removeAll()// 相当于str = ""
var str1 = "abcde"
//删除首尾指定位置内容
str1.removeFirst(3)
str1 //de
var str2 = "abcde"
str2.removeLast(3)
str2 //ab
3、改
//替换其中某些字符
let str = "abcde"
let str1 = str.replacingOccurrences(of: "cd", with: "fg")
str1 //abfge
//截取字符串
let str = "abcdefgh"
let str1 = String(str.prefix(2)) // 头部截取 ab
let str2 = String(str.suffix(3))// 尾部截取 fgh
//range截取,例如截取第2~5之间字符 cdef
let index1 = String.Index(utf16Offset:2,in:str)
let index2 = String.Index(utf16Offset:5,in:str)
let range = index1...index2
let range1 = index1..<index2
let str3 = String(str[range]) //cdef
let str4 = String(str[range1]) //cde
4、查
let str = "hello"
str[str.startIndex] // h
//是否包含某一个字符
let containStr = str.contains("e") //true
//判断字符串是否相等
let str1 : String = "abcdef"
let str2 = "ab"
str1.compare(str2).rawValue // 1
str1.compare(str).rawValue // -1
let str3 = str1 == str2 //false