Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

swift

I need a way to remove the first character from a string which is a space. I am looking for a method or even an extension for the String type that I can use to cut out a character of a string.

like image 922
dhruvm Avatar asked Feb 17 '15 20:02

dhruvm


People also ask

Which method removes all leading spaces in a string?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do you get rid of all whitespace in a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do you trim leading and trailing spaces in Swift?

Trim leading and trailing spaces To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.


2 Answers

To remove leading and trailing whitespaces:

let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Swift 3 / Swift 4:

let trimmedString = string.trimmingCharacters(in: .whitespaces)
like image 55
Alex Avatar answered Oct 01 '22 01:10

Alex


The correct way when you want to remove all kinds of whitespaces (based on this SO answer) is:

extension String {
    var stringByRemovingWhitespaces: String {
        let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
        return components.joinWithSeparator("")
    }
}

Swift 3.0+ (3.0, 3.1, 3.2, 4.0)

extension String {
    func removingWhitespaces() -> String {
        return components(separatedBy: .whitespaces).joined()
    }
}

EDIT

This answer was posted when the question was about removing all whitespaces, the question was edited to only mention leading whitespaces. If you only want to remove leading whitespaces use the following:

extension String {
    func removingLeadingSpaces() -> String {
        guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
            return self
        }
        return String(self[index...])
    }
}
like image 30
fpg1503 Avatar answered Oct 01 '22 01:10

fpg1503