KM的博客.

Swift字符串

字数统计: 324阅读时长: 1 min
2020/06/20

Swift5 字符串String

Swift version 5.2

Xcode11

1
let str = "WhelloKitty"

字符串截取前n个字符

1
2
3
4
5
let subStr1 = String(str.dropFirst())
print(subStr1) // helloKitty
let subStr2 = String(str.dropFirst(6))
print(subStr2) // Kitty

字符串截取?前的一部分

1
2
3
4
5
6
7
if let index = path.firstIndex(of: "?") {
let paramStr = path[path.index(after: index)..<path.endIndex]
// paramStr:"/xxx/xxx?"
print("paramStr is:\(String(paramStr.dropLast())")
// paramStr:"/xxx/xxx"

}

字符串截取?后的一部分

1
2
3
4
if let index = path.firstIndex(of: "?") {
let paramStr = path[path.index(after: index)..<path.endIndex]
print("paramStr is:\(paramStr)")
}

字符串截取后n个字符串

1
2
3
4
let subStr3 = String(str.dropLast())
print(subStr3) // WhelloKitt
let subStr4 = String(str.dropLast(5))
print(subStr4) // Whello

Extension

  • 通过URL中的query参数获取对应字典
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
extension String {

/// 通过URL中的query参数获取对应字典
/// ?time=2020-04&name=张三 =》{"time": "2020-04", "name": "张三" }
func getUrlParameters() -> [String: String]? {
var params: [String: String] = [:]

let array = self.components(separatedBy: "?")
if array.count == 2 {
let paramsStr = array[1]
if paramsStr.count > 0 {
let paramsArray = paramsStr.components(separatedBy: "&")
for param in paramsArray {
let arr = param.components(separatedBy: "=")
if arr.count == 2 {
params[arr[0]] = arr[1]
}
}
}
}

return params
}
/// 处理千分符号
/// 10000 => 10,000
func thousandsNumber(content: Double) -> String {
let format = NumberFormatter()
format.numberStyle = .decimal
format.usesGroupingSeparator = true
format.groupingSeparator = ","
format.groupingSize = 3
guard let result = format.string(for: NSNumber(value: content)) else { return "" }
return result
}

}

CATALOG
  1. 1. Swift5 字符串String
    1. 1.1. 字符串截取前n个字符
    2. 1.2. 字符串截取?前的一部分
    3. 1.3. 字符串截取?后的一部分
    4. 1.4. 字符串截取后n个字符串
    5. 1.5. Extension