一、字符串
- 读取字符串
let line = readLine()
while let line = readLine(){
...
}
- 字符串和Character数组互转
let line = readLine()
let array = Array(line)
let string = String(array)
- 字符串分割和截取
let line = readLine()
///分割
//1.根据字符分割
let subStrings = line.split(separator: " ")
//2.根据正则表达式分割
let subStrings = line.components(separatedBy: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
- 去除末尾字符
let line = readLine()
//去除头尾所有空格
let result = line.trimmingCharacters(in: .whitespaces)
//去除头尾指定的字符
let result = line.trimmingCharacters(in: CharacterSet(charactersIn: ",. "))
- 字符读取
//字符串转数组
let array:[Character] = Array(line)
//字符串字符unicode标量读取
let scalarView = line.unicodeScalars
for scalar in scalarView{
print(Int(scalar.value))
}
print(Int(scalarView.first!.value - "a".unicodeScalars.first!)) //这里可以用来定位字符,使用数组下标配合数组值来做哈希
二、数组
1.创建定长数组
var array = Array(repeating: 0, count: 10)
2.读取数组最大值、最小值(需要元素实现Comparable协议)
let min = array.min()
let max = array.max()
3.出入栈
//入栈
array.append(element)
//出栈
let element = array.popLast()
let elements = array.dropLast(3)
4.截取
//开区间,截取第0到第1两个元素
let elements = Array(array[0..<2])
//闭区间,截取第0到第2三个元素
let elements = Array(array[0...2])
5.在特定位置插入、删除、读取
std::vector<int> vec = {1, 2, 3, 4, 5};
// 在第三个位置(索引为2)插入元素
int value_to_insert = 10;
auto position_to_insert = vec.begin() + 2; // 指定位置的迭代器
vec.insert(position_to_insert, value_to_insert);
// 删除第三个位置的元素(索引为2)
auto position_to_remove = vec.begin() + 2; // 指定位置的迭代器
vec.erase(position_to_remove);
//读取第三个位置的元素
vec[2];
三、字典
1.移除某个键值对
dic.removeValue(forKey: key)