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– Alex2015-02-17 21:06:36 +00:00Commented Feb 17, 2015 at 21:06
- 1Possible duplicate: Remove whitespace character set from string excluding space.Imanou Petit– Imanou Petit2015-12-21 14:50:52 +00:00Commented Dec 21, 2015 at 14:50
33 Answers
To remove leading and trailing whitespaces:
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces) 5 Comments
NSCharacterSet.whitespaceAndNewlineCharacterSet() if you want to trim newline characters as well.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...]) } } 9 Comments
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. 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 Comments
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: "") 1 Comment
str.trimmingCharacters(in: .whitespacesAndNewlines) seems likes the simplest way. ThanksYou can also use regex.
let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil) 1 Comment
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: "") 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...
2 Comments
" First Word " outputs "First Word").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" 1 Comment
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 !" Comments
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 " 1 Comment
You can try This as well
let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-") 1 Comment
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." Comments
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) } Comments
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.
Comments
Swift 5+
Remove All whitespaces from prefix(start) of the string, you can use similar for suffix/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)) } } Comments
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.
Comments
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)] } } Comments
To Remove leading spaces from string
let exampleText = " \n\tHello world !" let regex = #/^\s*/# // regex finds any \s - symbols at the begging of the string let textWithoutSpacesInLeading = exampleText.replacing(regexSa) { _ in "" } // replace textWithoutSpacesInLeading == "Hello world !" // true Comments
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: "") } }