一、字符串
1、Character 字符类型
let chaA: Character = "好"
let chaB: Character = "B"
let chaC: Character = "\\"
print(chaA, chaB, chaC)
2、String 类型
let str1 = "Hello word"
var str2 = String()
print(str1)
print(str2)
if str2.isEmpty {
print("字符串是空的")
}
3、字符串长度计算
print("str1字符串长度:\(str1.count)")
4、遍历字符串
for c in str1 {
print(c)
}
5、链接字符串
let str3 = "my name is lila"
var str4 = str1 + "," + str3
print(str4)
str4 += "."
print(str4)
str4.append("好开心")
print(str4)
6、字符串的插值
let num10 = 10
let message = "\(num10)*2.5=\(Double(num10)*2.5)"
print(message)
7格式化字符串
let hour = 9
let minute = 10
let seconds = 22
let time = String(format: "%02d:%02d:%02d", hour, minute, seconds)
let time2 = String(format: "%01d:%04d:%03d", hour, minute, seconds)
print(time,time2)
8、字符串截取
let firstSpace = str4.firstIndex(of: " ") ?? str4.endIndex
let subStr1 = str4[..<firstSpace]
print(subStr1)
let someRange = str4.range(of: "lila")
let subStr3 = str4[someRange!]
print(subStr3)
print(str4[..<someRange!.lowerBound])
print(str4[someRange!.upperBound...])
let someRange3 = str4.range(of: "好开心")
print(str4[..<someRange3!.lowerBound])
print(str4[someRange3!.upperBound...])
let subStr2 = str4.split(separator: " ", maxSplits: 10, omittingEmptySubsequences: true)
print(subStr2)
9、比较字符串
let name1 = "lili"
let y = "lili"
if y == name1 {
print("一样的")
}
10、比较字符串前缀后缀
let httpStr = "https://swift.com.cn"
if httpStr.hasPrefix("http") { //前缀
print("http")
}
if httpStr.hasSuffix("cn") { //后缀
print("com")
}
二、数组
1、定义数组
//定义一个string类型的数组
var arr1:Array<String>
var arr2:[String]
2、创建空数组
var someInts = [Int]()
3、使用字面量构造数组
let names:[String] = ["lisa", "haojie", "sande"]
let arr3 = ["haozi", 17] as [Any]
print(arr3)
4、数组相加
arr1 = ["老大", "老二"]
arr2 = ["男", "女"]
var arr4 = arr1 + arr2
print(arr4)
5、数组长度、遍历
print(arr4.count)
for name in arr4{
print(name)
}
6、增加删除
arr4.append("ss")
print(arr4)
arr4.insert("aa", at: 2)
print(arr4)
arr4.remove(at: 0)
print(arr4)
arr4.removeLast()
print(arr4)
arr4.removeFirst()
print(arr4)
arr4.removeAll()
print(arr4)
7、使用下标法修改数组元素
var arr5 = arr3 + arr2
print(arr5)
arr5[0] = "ssssss"
print(arr5)
三、字典与集合
1、创建字典
var dic1:Dictionary<String, String> = ["name":"lili","age":"18"]
2、增加、替换
var dic2:Dictionary = ["name":"lili","age":18] as [String: Any]
dic2["name"] = "ak47"
print(dic2)
dic2["sex"] = "man"
print(dic2)
3、合并
var dic3 = ["title":"heheheheh"]
for (k,v) in dic3 {
dic2[k] = v
}
print(dic2)
dic2.removeValue(forKey: "sex")
print(dic2.keys)
print(Array(dic2.keys))
print(dic2.values)
print(Array(dic2.values))
网友评论