Bharathi
Bharathi

Reputation: 485

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.

Ex: ["Apple ", "Bike ", " Cat", " Dog "] I have an Array like this. I want all these spaces to be trimmed.

Upvotes: 5

Views: 4018

Answers (3)

vacawama
vacawama

Reputation: 154631

This is a good application for map. Use it to take each item in your array and apply trimmingCharacters(in:) to remove the whitespace from the ends of your strings.

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:

@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.

Upvotes: 14

Ahmet Ardal
Ahmet Ardal

Reputation: 1172

Swift 3-4 Compatible

(Based on @vacawama's answer)

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

Upvotes: 2

Bharathi
Bharathi

Reputation: 485

We can Join the array as a String, and can be replaced the space .

Like,

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

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

Upvotes: -2

Related Questions