我有一个 String
Array
需要修剪每个字符串中的空格..
请让我知道任何简单的方法,而无需将它们循环到 for 循环中。
例如:["Apple", "Bike", "Cat", "Dog"]
我有一个这样的 Array
。我希望修剪所有这些空间。
最佳答案
这是一个很好的 map
应用程序。使用它获取数组中的每个项目并应用 trimmingCharacters(in:)
删除字符串末尾的空格。
import Foundation // or UIKit or Cocoa
let array = ["Apple ", "Bike ", " Cat", " Dog "]
let trimmed = array.map { $0.trimmingCharacters(in: .whitespaces) }
print(trimmed) // ["Apple", "Bike", "Cat", "Dog"]
@DuncanC 的评论很重要,所以我在这里强调一下:
@vacawama's use of the map statement is certainly more "Swift-like" than using a for loop, but I bet the performance is all but identical. There is no magic here. If you need to check all the strings in an array and trim leading/trailing spaces then you need to iterate through all the strings. That is what the map statement does internally. It just uses functional rather than imperative syntax.
关于ios - Swift - 修剪数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37879939/