stringswift

How should I remove all the leading spaces from a 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.


Solution

  • To remove leading and trailing whitespaces:

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

    Swift 3 / Swift 4:

    let trimmedString = string.trimmingCharacters(in: .whitespaces)