Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Trim String in Array

Tags:

arrays

ios

swift

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.

like image 963
Bharathi Avatar asked Jun 17 '16 11:06

Bharathi


People also ask

How do I remove spaces from a string in Swift?

To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered. append(character) } } print(filtered) // "Hello, World! "

How do I separate a string from a character in Swift?

To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.


1 Answers

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.

like image 180
vacawama Avatar answered Sep 23 '22 13:09

vacawama