ios - Swift - 修剪数组中的字符串

标签 ios arrays swift

我有一个 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/

相关文章:

c++ - 不能对二维数组使用 find()

ios - 升级到 XCode 13(和 iOS 15)后选项卡和导航栏发生变化

ios - 如何对 iOS View Controller 进行单元测试?

arrays - 下标的使用不明确

ios - 如何构建适用于 ios 7 和 ios 8 的应用程序?

javascript - 在 Javascript 中实例化数组后定义其初始数据的最佳方法是什么?

Swift:使用弱 self 在基于 block 的执行中保持原子性

ios - 如何显示步骤进度条

javascript - 自动选择输入字段

ios - 无法使用 PushKit 接收 VoIP 通知