[string] 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.

This question is related to string swift

The answer is


Swift 3 version of BadmintonCat's answer

extension String {
    func replace(_ string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(" ", replacement: "")
    }
}

For me, the following line used to remove white space.

let result = String(yourString.filter {![" ", "\t", "\n"].contains($0)})

You can also use regex.

let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)

Trimming white spaces in Swift 4

let strFirstName = txtFirstName.text?.trimmingCharacters(in: 
 CharacterSet.whitespaces)

To remove all spaces from the string:

let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!

If anybody remove extra space from string e.g = "This is the demo text remove extra space between the words."

You can use this Function in Swift 4.

func removeSpace(_ string: String) -> String{
    var str: String = String(string[string.startIndex])
    for (index,value) in string.enumerated(){
        if index > 0{
            let indexBefore = string.index(before: String.Index.init(encodedOffset: index))
            if value == " " && string[indexBefore] == " "{
            }else{
                str.append(value)
            }
        }
    }
    return str
}

and result will be

"This is the demo text remove extra space between the words."

You can try This as well

   let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")

I'd use this extension, to be flexible and mimic how other collections do it:

extension String {
    func filter(pred: Character -> Bool) -> String {
        var res = String()
        for c in self.characters {
            if pred(c) {
                res.append(c)
            }
        }
        return res
    }
}

"this is a String".filter { $0 != Character(" ") } // "thisisaString"

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...])
    }
}

This String extension removes all whitespace from a string, not just trailing whitespace ...

 extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(string: " ", replacement: "")
    }
  }

Example:

let string = "The quick brown dog jumps over the foxy lady."
let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady.

For anyone looking for an answer to remove only the leading whitespaces out of a string (as the question title clearly ask), Here's an answer:

Assuming:

let string = "   Hello, World!   "

To remove all leading whitespaces, use the following code:

var filtered = ""
var isLeading = true
for character in string {
    if character.isWhitespace && isLeading {
        continue
    } else {
        isLeading = false
        filtered.append(character)
    }
}
print(filtered) // "Hello, World!   "

I'm sure there's better code than this, but it does the job for me.


Yet another answer, sometimes the input string can contain more than one space between words. If you need to standardize to have only 1 space between words, try this (Swift 4/5)

let inputString = "  a very     strange   text !    "
let validInput = inputString.components(separatedBy:.whitespacesAndNewlines).filter { $0.count > 0 }.joined(separator: " ")

print(validInput) // "a very strange text !"

Try functional programming to remove white spaces:

extension String {
  func whiteSpacesRemoved() -> String {
    return self.filter { $0 != Character(" ") }
  }
}

For Swift 3.0+ see the other answers. This is now a legacy answer for Swift 2.x

As answered above, since you are interested in removing the first character the .stringByTrimmingCharactersInSet() instance method will work nicely:

myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

You can also make your own character sets to trim the boundaries of your strings by, ex:

myString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))

There is also a built in instance method to deal with removing or replacing substrings called stringByReplacingOccurrencesOfString(target: String, replacement: String). It can remove spaces or any other patterns that occur anywhere in your string

You can specify options and ranges, but don't need to:

myString.stringByReplacingOccurrencesOfString(" ", withString: "")

This is an easy way to remove or replace any repeating pattern of characters in your string, and can be chained, although each time through it has to take another pass through your entire string, decreasing efficiency. So you can do this:

 myString.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString(",", withString: "")

...but it will take twice as long.

.stringByReplacingOccurrencesOfString() documentation from Apple site

Chaining these String instance methods can sometimes be very convenient for one off conversions, for example if you want to convert a short NSData blob to a hex string without spaces in one line, you can do this with Swift's built in String interpolation and some trimming and replacing:

("\(myNSDataBlob)").stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")).stringByReplacingOccurrencesOfString(" ", withString: "")

Hi this might be late but worth trying. This is from a playground file. You can make it a String extension.

This is written in Swift 5.3

Method 1:

var str = "\n \tHello, playground       "
if let regexp = try? NSRegularExpression(pattern: "^\\s+", options: NSRegularExpression.Options.caseInsensitive) {
    let mstr = NSMutableString(string: str)
    regexp.replaceMatches(in: mstr, options: [], range: NSRange(location: 0, length: str.count), withTemplate: "")
    str = mstr as String
}

Result: "Hello, playground       "

Method 2:

if let c = (str.first { !($0 == " " || $0 == "\t" || $0 == "\n") }) {
    if let nonWhiteSpaceIndex = str.firstIndex(of: c) {
        str.replaceSubrange(str.startIndex ..< nonWhiteSpaceIndex, with: "")
    }
}

Result: "Hello, playground       "

Swift 4

The excellent case to use the regex:

" this is    wrong contained teee xt     "
    .replacingOccurrences(of: "^\\s+|\\s+|\\s+$", 
                          with: "", 
                          options: .regularExpression)

// thisiswrongcontainedteeext

Swift 4, 4.2 and 5

Remove space from front and end only

let str = "  Akbar Code  "
let trimmedString = str.trimmingCharacters(in: .whitespacesAndNewlines)

Remove spaces from every where in the string

let stringWithSpaces = " The Akbar khan code "
let stringWithoutSpaces = stringWithSpaces.replacingOccurrences(of: " ", with: "")

extension String {

    var removingWhitespaceAndNewLines: String {
        return removing(.whitespacesAndNewlines)
    }

    func removing(_ forbiddenCharacters: CharacterSet) -> String {
        return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
    }
}

class SpaceRemover
{
    func SpaceRemover(str :String)->String
    {
        var array = Array(str)
        var i = array.count
        while(array.last == " ")
        {
            var array1 = [Character]()
            for item in  0...i - 1
            {
                array1.append(array[item])
            }
            i = i - 1
            array = array1
            print(array1)
            print(array)

        }

        var arraySecond = array
        var j = arraySecond.count

        while(arraySecond.first == " ")
        {
            var array2 = [Character]()
            if j > 1
            {
                for item in 1..<j
                {
                    array2.append(arraySecond[item])
                }
            }
            j = j - 1
            arraySecond = array2
            print(array2)
            print(arraySecond)

        }
        print(arraySecond)
        return String(arraySecond)
    }
}

If you are wanting to remove spaces from the front (and back) but not the middle, you should use stringByTrimmingCharactersInSet

    let dirtyString   = " First Word "
    let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

If you want to remove spaces from anywhere in the string, then you might want to look at stringByReplacing...


Swift 3

You can simply use this method to remove all normal spaces in a string (doesn't consider all types of whitespace):

let myString = " Hello World ! "
let formattedString = myString.replacingOccurrences(of: " ", with: "")

The result will be:

HelloWorld!

For swift 3.0

import Foundation

var str = " Hear me calling"

extension String {
    var stringByRemovingWhitespaces: String {
        return components(separatedBy: .whitespaces).joined()
    }
}

str.stringByRemovingWhitespaces  // Hearmecalling

string = string.filter ({!" ".contains($0) })

Swift 3 version

  //This function trim only white space:
   func trim() -> String
        {
            return self.trimmingCharacters(in: CharacterSet.whitespaces)
        }
    //This function trim whitespeaces and new line that you enter:
     func trimWhiteSpaceAndNewLine() -> String
        {
            return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        }