字符串如何移除奇數位置的字符swift
熟悉基本語法,第一個答案給的很簡潔,學習學習數組
let string = "helloworld"
let newString = string.enumerated().filter({ $0.0 % 2 != 0 }).map({ String($0.element) }).joined()
複製代碼
enumerated
和for in
結合起來作遍歷bash
let string = "helloworld"
for element in string.enumerated() {
print(element)
}
複製代碼
能夠獲得的元組(offset, element)
學習
(offset: 0, element: "h")
(offset: 1, element: "e")
(offset: 2, element: "l")
(offset: 3, element: "l")
(offset: 4, element: "o")
(offset: 5, element: "w")
(offset: 6, element: "o")
(offset: 7, element: "r")
(offset: 8, element: "l")
(offset: 9, element: "d")
複製代碼
filter
過濾出奇數位置的數組,每一個元素也是元組(offset, element)
ui
簡寫$0
= 元組(offset, element)
, $0.0
= 元組.offset
, $0.1
= 元組.element
spa
let element = string.enumerated().filter({ $0.0 % 2 != 0})
print(element)
複製代碼
打印code
[
(offset: 1, element: "e"),
(offset: 3, element: "l"),
(offset: 5, element: "w"),
(offset: 7, element: "r"),
(offset: 9, element: "d")]
複製代碼
map
至關於從新對每一個元素作改造,如今每一個數組元素是元組,先把每一個元素改形成字符串element
let element = string.enumerated().filter({ $0.0 % 2 != 0}).map({ String($0.element) })
// 或 string.enumerated().filter({ $0.0 % 2 != 0}).map({ String($0.1) })
print(element)
複製代碼
打印rem
["e", "l", "w", "r", "d"]
複製代碼
joined
將數組的每一個元素鏈接在一塊兒字符串
let element = string.enumerated().filter({ $0.0 % 2 != 0}).map({ String($0.1) }).joined()
print(element)
複製代碼
打印
elwrd
複製代碼