**:
1.擷取前面三個字串,要求輸出結果為abc
let str ="abcdefghi"
let index = str.index(str.startindex, offsetby:3)//獲取字元d的索引
let result = str.substring(to: index)//從起始擷取到索引的所有字串,即abc,注意不包含d
列印結果為 abc
2.擷取第四個開始的所有字串,要求輸出結果為defghi
let str = "abcdefghi"
let index = str.index(str.startindex, offsetby: 3)//獲取字元d的索引
let result = str.substring(from: index)//從d的索引開始擷取後面所有的字串即defghi
列印結果為defghi
3.擷取第4個開始的長度為2個字串,要求結果輸出為de
let str ="abcdefghi"
let startindex = str.index(str.startindex, offsetby:3)//獲取d的索引
let endindex = str.index(startindex, offsetby:2)//從d的索引開始往後兩個,即獲取f的索引
let result = str.substring(with: startindex..列印結果為de
4.判斷字串是否包含某段字元
let str = "abcdefghi"
let result = str.contains("ac")
列印結果為false
let result = str.contains("abc")
列印結果為true
5.字串大小寫轉換
let str = "abcdefghi"
let result = str.lowercased()
輸出結果為abcdefghi
let str = "abcdefghi"
let result = str.uppercased()
輸出結果為abcdefghi
6.指定字串替換為其他字串,將abc替換成m,使輸出結果為mdefghi
let str = "abcdefghi"
let result = str.replacingoccurrences(of:"abc", with: "m")
輸出結果為mdefghi
7.指定範圍內的字串替換為其他字串,將cde替換成m,使輸出結果為abmfghi
let str = "abcdefghi"
let startindex = str.index(str.startindex, offsetby:2)
let endindex = str.index(startindex, offsetby:3)
let result = str.replacingcharacters(in: startindex..輸出結果為abmfghi
8.有時候不確定字串的長度,需求為擷取字串末尾面開始往前5位,擷取長度為2的字串,使輸出為ef
let str = "abcdefghi"
let startindex = str.index(str.startindex, offsetby: str.lengthofbytes(using: .utf8) - 5)
let endindex = str.index(startindex, offsetby:2)
let result = str.substring(with: startindex..輸出結果為ef
9. 字串轉為陣列,使得輸出為["a", "b", "c", "d", "e", "f", "g", "h", "i"]
let str = "a.b.c.d.e.f.g.h.i"
let result = str.components(separatedby:".")
輸出為["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Swift3 0 字串常用整理
swift3.0 字串常用整理 1 判斷前字尾,hasperfix,hassuffix 返回的是bool值 str.hasprefix www.字首 str.hassuffix com 字尾 2 判斷兩個字串是否相等,返回的是bool值 let str1 www let str2 com if st...
swift3 0 關於字串
playground noun a place where people can play import uikit 字串字面量 func zfczml unicode 標量 u 0024 u unicode 標量 u 2665 u unicode 標量 u 1f496 初始化空字串 func cs...
擷取字串
static function blogsummary str,len 100 else out valtmp break tmp tmpstr outlen mb strlen valtmp,charset out val.rs 2 key right rs 2 key unset rs tags...