skip to Main Content

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 nr in a String?

Any help would be greatly appreciated.

Thanks in advance.

3

Answers


  1. You can use this:

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

    output:
    "Test User Image"

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search