-1

How can I remove all white space from the beginning and end of a string?

Like so:

"Test User Image" returns "Test User Image"

"Test User Image " returns "Test User Image"

" Test User Image " returns "Test User Image"

" Test User Image " returns "Test User Image"

Question: How to remove all the white spaces from a string at the beginning or end?

Can someone please explain to me how to remove all the white spaces, I've tried with the below answers but no results yet.

How should I remove all the leading spaces from a string? - swift

How to remove all the spaces and \n\r in a String?

Any help would be greatly appreciated.

Thanks in advance.

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59

3 Answers3

1

You can use this:

let str = "    Test    User    Image   "
str.trimmingCharacters(in: .whitespacesAndNewlines)

output: "Test User Image"

Ali Moazenzadeh
  • 584
  • 4
  • 13
  • No, the output is `"Test User Image"`. `trim` does not remove spaces between two other characters. And if it did the output would be `"TestUserImage"`. But it answers the question. – vadian Feb 28 '23 at 09:00
0

Please check it out,

let name = " I am Abhijit "
let trim = name.trimmingCharacters(in: .whitespaces)
print(trim)
print(name.count)
print(trim.count)

I hope you got the answer.

0

You can use name.trimmingCharacters(in:) using the WhiteSpace character set as parameter, but this has a cost because it calls the underlying NSString function.

A pure Swift implementation may look as below:

extension String {

    func trimmedWS() -> String {
        guard let start = firstIndex(where: { !$0.isWhitespace }) else {
            return ""
        }
        let reversedPrefix = suffix(from: start).reversed()
        let end = reversedPrefix.firstIndex(where: { !$0.isWhitespace })!
        let trimmed = reversedPrefix.suffix(from: end).reversed()
        return String(trimmed)
    }

}
print(" Test User Image   ".trimmedWS())

Prints: "Test User Image"

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67