简体   繁体   English

Swift - 在数组中修剪字符串

[英]Swift - Trim String in Array

I have a String Array where I have need to trim the Spaces in each string.. Please let me know for any simple way without looping them in for loop. 我有一个String Array ,我需要修剪每个字符串中的空格..请告诉我任何简单的方法,而不是循环它们for循环。

Ex: ["Apple ", "Bike ", " Cat", " Dog "] I have an Array like this. 例如: ["Apple ", "Bike ", " Cat", " Dog "]我有一个像这样的Array I want all these spaces to be trimmed. 我想要修剪所有这些空间。

This is a good application for map . 这是一个很好的map应用程序。 Use it to take each item in your array and apply trimmingCharacters(in:) to remove the whitespace from the ends of your strings. 使用它来获取数组中的每个项目并应用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's comment is an important point so I'm highlighting it here: @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. @ vacawama使用map语句肯定比使用for循环更像“Swift-like”,但我敢打赌,性能几乎完全相同。 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. 这就是map语句在内部的作用。 It just uses functional rather than imperative syntax. 它只使用功能而不是命令式语法。

Swift 3-4 Compatible Swift 3-4兼容

(Based on @vacawama's answer) (根据@ vacawama的回答)

let items =  ["Apple ", "Bike ", " Cat", " Dog "]
let trimmed = items.map({
  return $0.trimmingCharacters(in: .whitespaces)
})
print(trimmed)  // ["Apple", "Bike", "Cat", "Dog"]

We can Join the array as a String, and can be replaced the space . 我们可以将数组作为String加入,并且可以替换空格。

Like, 喜欢,

 let array =  ["Apple ", "Bike ", " Cat", " Dog "]
 var jointString = array.joinWithSeparator(",")
 jointString = jointString.stringByReplacingOccurrencesOfString(" ", withString: "")

 let newArray = jointString.componentsSeparatedByString(",")
 print(newArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM