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

1
  • 3
    Add the code you have tried, the solutions in the linked questions works so it’s very unclear why it isn’t working for you Commented Feb 28, 2023 at 7:50

3 Answers 3

2

You can use this:

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

output: "Test User Image"

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.