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.
-
8Do you want to remove the first space character or _all_ space characters in the string? – Alex Feb 17 '15 at 21:06
-
1Possible duplicate: [Remove whitespace character set from string excluding space](http://stackoverflow.com/q/26963379/1966109). – Imanou Petit Dec 21 '15 at 14:50
32 Answers
To remove leading and trailing whitespaces:
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces)

- 8,801
- 5
- 27
- 31
-
213this will only work for leading and trailing whitespaces. this will not remove the whitespaces contained in string. – sun May 24 '15 at 22:38
-
101if you wanna remove all blank spaces you can try myString.stringByReplacingOccurrencesOfString(" ", withString: "") – Lucas Jul 18 '15 at 16:52
-
7You could also use `NSCharacterSet.whitespaceAndNewlineCharacterSet()` if you want to trim newline characters as well. – Blip Jul 28 '15 at 23:54
-
2To make it work with Swift 3.0 and also remove white spaces in between string, use answer: http://stackoverflow.com/a/39067610/4886069 – Oct 07 '16 at 10:49
-
3Swift 3+ user: yourString.replacingOccurrences(of: " ", with: "") – Nadeesha Lakmal Nov 08 '17 at 10:21
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...])
}
}

- 7,492
- 6
- 29
- 49
-
6also .components(separatedBy: .whitespacesAndNewlines) for new lines too – Derek Jan 18 '17 at 10:29
-
-
-
1**Because of the logic of the feature**. You are making a *calculated property* when you should make a *function*. It is doing smt rather then holding a value or calculate it from another one. Look at: http://stackoverflow.com/questions/24035276/computed-read-only-property-vs-function-in-swift – Jakub Truhlář Jan 20 '17 at 17:44
-
4@JakubTruhlář - That's a matter of opinion, not a statement of fact. See https://softwareengineering.stackexchange.com/questions/304077/swift-functions-vs-computed-properties – Ashley Mills Aug 08 '17 at 11:35
-
@AshleyMills And where exactly I say it is a fact and you must follow that? I pointed that, because the function makes more sense here. – Jakub Truhlář Aug 08 '17 at 13:17
-
1@JakubTruhlář You say _"This should be a func not a var"_ - this sounds very much like you are stating a fact, not your opinion. If you read the answers to the linked question, you'll see that while it "makes sense" to you, to other people… not necessarily. – Ashley Mills Aug 08 '17 at 13:22
-
@AshleyMills "should". Answers to the question, the most people agreed with says - it makes more sense, however it is matter of style. But it is not the purpose of this Q after all. – Jakub Truhlář Aug 08 '17 at 13:44
-
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.

- 3,517
- 5
- 26
- 44

- 9,416
- 14
- 78
- 129
-
4
-
-
The ones defined on the Zs category: fileformat.info/info/unicode/category/Zs/list.htm – fpg1503 Aug 29 '17 at 15:15
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!

- 2,932
- 2
- 23
- 30

- 1,195
- 13
- 13
-
1
-
@Greg you're still missing 16 other characters: http://www.fileformat.info/info/unicode/category/Zs/list.htm – fpg1503 Dec 30 '16 at 03:43
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: "")

- 2,215
- 19
- 27
-
`str.trimmingCharacters(in: .whitespacesAndNewlines)` seems likes the simplest way. Thanks – Rizwan Walayat Feb 15 '23 at 13:40
You can also use regex.
let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)

- 1,396
- 1
- 9
- 21
-
Swift 4: myString.replacingOccurrences(of: "\\s", with: "", options: NSString.CompareOptions.regularExpression, range: nil) – norbDEV Jan 27 '19 at 12:28
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: "")

- 997
- 1
- 9
- 24
-
-
It still doesn't consider other kinds of whitespace in the middle of the String – fpg1503 Mar 03 '17 at 12:43
For swift 3.0
import Foundation
var str = " Hear me calling"
extension String {
var stringByRemovingWhitespaces: String {
return components(separatedBy: .whitespaces).joined()
}
}
str.stringByRemovingWhitespaces // Hearmecalling

- 229,809
- 59
- 489
- 571

- 71,228
- 33
- 160
- 165
Swift 4
The excellent case to use the regex:
" this is wrong contained teee xt "
.replacingOccurrences(of: "^\\s+|\\s+|\\s+$",
with: "",
options: .regularExpression)
// thisiswrongcontainedteeext

- 12,093
- 5
- 62
- 45
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"

- 946
- 10
- 8

- 59,296
- 21
- 173
- 234
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...

- 3,342
- 1
- 16
- 17
-
-
@NikhilGupta no, only leading and trailing (the example `" First Word "` outputs `"First Word"`). – fpg1503 Oct 31 '16 at 09:35
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 !"

- 15,384
- 5
- 35
- 44
Try functional programming to remove white spaces:
extension String {
func whiteSpacesRemoved() -> String {
return self.filter { $0 != Character(" ") }
}
}

- 41
- 2
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 "

- 83
- 6
You can try This as well
let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")

- 797
- 9
- 19
extension String {
var removingWhitespaceAndNewLines: String {
return removing(.whitespacesAndNewlines)
}
func removing(_ forbiddenCharacters: CharacterSet) -> String {
return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
}
}

- 19,885
- 13
- 86
- 90
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."

- 655
- 9
- 18
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)
}

- 169
- 1
- 2
- 10
Trimming white spaces in Swift 4
let strFirstName = txtFirstName.text?.trimmingCharacters(in:
CharacterSet.whitespaces)

- 797
- 9
- 9
OK, this is old but I came across this issue myself and none of the answers above worked besides removing all white spaces which can be detrimental to the functionality of your app. My issue was like so:
["This", " is", " my", " array", " it is awesome"]
If trimmed all white spaces this would be the output:
["This", "is", "my", "array", "itisawesome"]
So I needed to eliminate the leading spacing and simply switching from:
let array = jsonData.components(separatedBy: ",")
To
let array = jsonData.components(separatedBy: ", ")
Fixed the issue. Hope someone find this useful in the future.

- 555
- 6
- 17
For me, the following line used to remove white space.
let result = String(yourString.filter {![" ", "\t", "\n"].contains($0)})

- 1,299
- 2
- 14
- 31
This worked for me in swift 5
var myString = " Kwame Ch ef "
myString = myString.replacingOccurrences(of: " ", with: "")
print(myString)
output: Kwame Chef

- 123
- 1
- 2
- 17
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.

- 761
- 9
- 23
Swift 5+ Remove All whitespace from prefix(start) of the string, you can use similar for sufix/end of the string
extension String {
func deletingPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
func removeWhitespacePrefix() -> String {
let prefixString = self.prefix(while: { char in
return char == " "
})
return self.deletingPrefix(String(prefixString))
}
}

- 2,462
- 2
- 29
- 31
Removing leading space (including newlines) –without touching anything else!
var string = " ABC"
if let index = string.firstIndex(where: { char in !char.isWhitespace }) {
string = String(string[index...]) // "ABC"
}

- 62,815
- 21
- 164
- 192
Really FAST solution:
usage:
let txt = " hello world "
let txt1 = txt.trimStart() // "hello world "
let txt2 = txt.trimEnd() // " hello world"
usage 2:
let txt = "rr rrr rrhello world r r r r r r"
let txt1 = txt.trimStart(["r", " "]) // "hello world r r r r r r"
let txt2 = txt.trimEnd(["r", " "]) // "rr rrr rrhello world"
if you need to remove ALL whitespaces from string:
txt.replace(of: " ", to: "")
public extension String {
func trimStart(_ char: Character) -> String {
return trimStart([char])
}
func trimStart(_ symbols: [Character] = [" ", "\t", "\r", "\n"]) -> String {
var startIndex = 0
for char in self {
if symbols.contains(char) {
startIndex += 1
}
else {
break
}
}
if startIndex == 0 {
return self
}
return String( self.substring(from: startIndex) )
}
func trimEnd(_ char: Character) -> String {
return trimEnd([char])
}
func trimEnd(_ symbols: [Character] = [" ", "\t", "\r", "\n"]) -> String {
var endIndex = self.count - 1
for i in (0...endIndex).reversed() {
if symbols.contains( self[i] ) {
endIndex -= 1
}
else {
break
}
}
if endIndex == self.count {
return self
}
return String( self.substring(to: endIndex + 1) )
}
}
/////////////////////////
/// ACCESS TO CHAR BY INDEX
////////////////////////
extension StringProtocol {
subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
subscript(range: Range<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: ClosedRange<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] }
}

- 9,318
- 5
- 65
- 101
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: "")
}
}

- 131
- 1
- 10
-
-
Because your answer is wrong. The answer you've provided an update to is also wrong. There are several kinds of whitespaces and that's why using `whitespaceCharacterSet` is a best practice. – fpg1503 Aug 23 '16 at 10:24
To remove all spaces from the string:
let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!

- 2,362
- 1
- 17
- 20
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)
}
}
Technically not an answer to the original question but since many posts here give an answer for removing all whitespace, here is an updated, more concise version:
let stringWithouTAnyWhitespace = string.filter {!$0.isWhitespace}

- 7,068
- 3
- 40
- 69