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.
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! "
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With