數(shù)組與字符串的互轉(zhuǎn), 以下為代碼示例
數(shù)組轉(zhuǎn)字符串
//字符串?dāng)?shù)組按元素拼接成字符串
let stringArray = ["1", "2", "3", "4"]
//不帶參數(shù)方法
let resultString1 = stringArray.joined()
print(resultString1)
//打印結(jié)果:"1234"
//帶參數(shù)方法, 用指定字符或字符串分隔而組成的結(jié)果字符串
let resultString2 = stringArray.joined(separator: ",")
print(resultString2)
//打印結(jié)果:"1,2,3,4"
字符串轉(zhuǎn)數(shù)組
- 無分隔符方式
let string = "abcd"
//數(shù)組自帶方法, 用字符串生成單字符組成的數(shù)組
let strArray1 = Array(string)
print(strArray1)
//打印結(jié)果:["a", "b", "c", "d"]
//字符串方法
let strArray2 = string.compactMap { (item) -> String in
return "\(item)"
}
print(strArray2)
//打印結(jié)果:["a", "b", "c", "d"]
- 有分隔符方式, 示例以字符串中字母"c"為分隔符分割整體字符串為數(shù)組
let splitString1 = "abccdabccdabcd"
//方法1: 如果字符串中存在兩個(gè)相鄰的分隔符, 則不保留空字符串
let splitArray1 = splitString1.split(separator: "c")
print(splitArray1)
//打印結(jié)果:["ab", "dab", "dab", "d"]
//方法2: 如果字符串中存在兩個(gè)相鄰的分隔符, 則保留空字符串
let splitString2 = "abccdabccdabcd"
let splitArray2 = splitString2.components(separatedBy: "c")
print(splitArray2)
//打印結(jié)果:["ab", "", "dab", "", "dab", "d"]