欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift4:字符串操作,数组操作

程序员文章站 2022-07-14 19:41:27
...
var str = "Hello, playground"
取前3个字符
str.prefix(3) // Hel
取后3个字符
str.suffix(3) // und
遍历字符串
var swift = "Swift 很有趣"
for (index , value) in swift.enumerated(){
    print("index is \(index), value is \(value)")
}
插入字符串
if let index = swift.index(of: " "){
    swift.insert(contentsOf: " 3.0", at: index) // Swift 3.0 很有趣
}
替换字符串
if let index = swift.index(of: "很"){
    swift.replaceSubrange(index ..< swift.endIndex, with: "is interesting!") // Swift 3.0 is interesting!
}
字符串切片,获取interesting
swift.suffix(12).dropLast() // interesting
字符串切片,按照空格分隔
swift.split(separator: " ") // ["Swift", "3.0", "is", "interesting!"]
奇数位切割,只取偶数
var i = 0
let singles = swift.split { _ in
    if i > 0 {
        i = 0
        return true
    }else{
        i = 1
        return false
    }
    return false
}
singles.map(String.init) // ["S", "i", "t", "3", "0", "i", " ", "n", "e", "e", "t", "n", "!"]
Tuple
let success = ("1", "2")
let failed = ("2.0.9", "3.0.0")
success.0 < failed.0
forin
for _ in 0 ..< 5{
    print(i) // 0,1,2,3,4
}

数组
let array = [1,2,3,4,5] // 不可变数组
var array = [1,2,3,4,5] // 可变数组
每个元素相乘
// 每个元素相乘
let constSquares = array.map{$0 * $0}
取得数组里面最小的元素
constSquares.min() // 1
取得数组里最大的元素
constSquares.max() // 25
排序
constSquares.sorted(by:>)  // 从大到小排序 25,16,9,4,1
constSquares.sorted(by:<) ,constSquares.sorted()// 从小到大排序 1,4,9,16,25
筛选满足条件的元素
// 选出偶数
let even = constSquares.filter{$0 % 2 == 0} // 4,16

//  filter语义的常用操作是判断数组中是否存在满足条件的元素
let contain = array.filter {$0 % 2 == 0}.count > 0 // true
遍历数组
// 遍历数组的每一个元素
constSquares.forEach{
    print($0) // 1,4,9,16,25
}
contains(判断数组是否包含满足条件的元素)
//  contains的一个好处就是只要遇到满足条件的元素,函数的执行就终止了
array.contains{$0 % 2 == 0} // true(是否包含偶数)
reduce
array.reduce(0, +) // 计算数组里的和 15
Map
map用于将每个数组元素通过某个方法进行转换。
Filter
filter用于选择数组元素中满足某种条件的元素。
Reduce
reduce方法把数组元素组合计算为一个值。