Swift5.0 关于数组的常用方法总结

数组与字符串的互转, 以下为代码示例

数组转字符串

//字符串数组按元素拼接成字符串
let stringArray = ["1", "2", "3", "4"]
//不带参数方法
let resultString1 = stringArray.joined()
print(resultString1)
//打印结果:"1234"
//带参数方法, 用指定字符或字符串分隔而组成的结果字符串
let resultString2 = stringArray.joined(separator: ",")
print(resultString2)
//打印结果:"1,2,3,4"

字符串转数组

  1. 无分隔符方式
    let string = "abcd"
    //数组自带方法, 用字符串生成单字符组成的数组
    let strArray1 = Array(string)
    print(strArray1)
    //打印结果:["a", "b", "c", "d"]
    //字符串方法
    let strArray2 = string.compactMap { (item) -> String in
        return "\(item)"
    }
    print(strArray2)
    //打印结果:["a", "b", "c", "d"]
  1. 有分隔符方式, 示例以字符串中字母"c"为分隔符分割整体字符串为数组
    let splitString1 = "abccdabccdabcd"
    //方法1:  如果字符串中存在两个相邻的分隔符, 则不保留空字符串
    let splitArray1 = splitString1.split(separator: "c")
    print(splitArray1)
    //打印结果:["ab", "dab", "dab", "d"]
    //方法2: 如果字符串中存在两个相邻的分隔符, 则保留空字符串
    let splitString2 = "abccdabccdabcd"
    let splitArray2 = splitString2.components(separatedBy: "c")
    print(splitArray2)
    //打印结果:["ab", "", "dab", "", "dab", "d"]

你可能感兴趣的:(Swift5.0 关于数组的常用方法总结)