我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特

我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。

212521 次浏览

我会使用这个扩展,以灵活和模仿其他集合如何做到这一点:

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"

删除开头和结尾的空格:

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

Swift 3 / Swift 4:

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

如果你想要删除前面(和后面)的空格,而不是中间,你应该使用stringByTrimmingCharactersInSet

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

如果你想从字符串的任何地方删除空格,那么你可能需要查看stringbyreplacement…

这个String扩展删除了字符串中的所有空格,而不仅仅是尾随空格…

 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: "")
}
}

例子:

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

关于Swift 3.0+,请参阅其他答案。这是Swift 2.x现在的一个遗留答案

如上所述,由于你对删除第一个字符感兴趣,.stringByTrimmingCharactersInSet ()实例方法将很好地工作:

myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

你也可以让你自己的字符集来修剪你的字符串的边界,例如:

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

还有一个内置的实例方法来处理删除或替换子字符串,称为stringByReplacingOccurrencesOfString(目标:字符串,替换:字符串)。它可以删除字符串中任何地方出现的空格或任何其他模式

你可以指定选项和范围,但不需要:

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

这是一种简单的方法,可以删除或替换字符串中任何重复的字符模式,并且可以被链接,尽管每次遍历它都必须再次遍历整个字符串,从而降低了效率。所以你可以这样做:

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

...但要花两倍的时间。

.stringByReplacingOccurrencesOfString()文档from Apple site . >.stringByReplacingOccurrencesOfString(

链接这些String实例方法有时可以非常方便地进行一次性转换,例如,如果你想将一个短的NSData blob转换为一行中没有空格的十六进制字符串,你可以使用Swift内置的String插值和一些修剪和替换:

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

你也可以使用正则表达式。

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

你也可以试试这个

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

羽毛球猫的答案的Swift 3版本

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: "")
}
}

当你想要删除所有类型的空白(基于这个SO答案)时,正确的方法是:

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()
}
}

编辑

这个答案是在关于删除所有空白的问题时发布的,该问题被编辑为只提到前导空白。如果你只想删除前导空白,请使用以下方法:

extension String {
func removingLeadingSpaces() -> String {
guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
return self
}
return String(self[index...])
}
}

对于斯威夫特3.0

import Foundation


var str = " Hear me calling"


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


str.stringByRemovingWhitespaces  // Hearmecalling

斯威夫特3

你可以简单地使用这个方法删除字符串中的所有正常的空格(不考虑所有类型的空格):

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

结果将是:

HelloWorld!

Swift 3版本

  //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)
}

删除字符串中的所有空格:

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

尝试函数式编程来删除空白:

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


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


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

如果有人从字符串中删除额外的空格,例如:"This is the demo text remove extra space between the words."

你可以在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
}

结果是

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

斯威夫特4

使用正则表达式的最佳情况:

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


// thisiswrongcontainedteeext

在Swift 4修剪空白

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

对我来说,下面这行用来删除空白。

let result = String(yourString.filter {![" ", "\t", "\n"].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)
}
}

另一个答案是,有时输入字符串在单词之间可以包含多个空格。如果你需要标准化,单词之间只有一个空格,试试这个(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 !"
string = string.filter ({!" ".contains($0) })

Swift 4、4.2和5

仅从前端和尾部移除空间

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

从字符串中的每一个地方删除空格

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

嗨,这可能有点晚,但值得一试。这是一个游乐场的文件。你可以让它成为一个字符串扩展名。

这是在Swift 5.3中编写的

方法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       "

方法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       "

对于任何寻找从字符串中删除只有前导空格的答案的人(正如问题标题清楚地要求的那样),这里有一个答案:

假设:

let string = "   Hello, World!   "

要删除所有前导空格,使用以下代码:

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

我相信有比这更好的代码,但它已经完成了我的工作。

< p >迅速5 + 从字符串的前缀(开始)删除所有空白,你可以使用类似的后缀/结束字符串

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

代码少做多。

"Hello World".filter({$0 != " "}) // HelloWorld

快速解决方案:

用法:

let txt = "        hello world     "
let txt1 = txt.trimStart() // "hello world     "
let txt2 = txt.trimEnd()   // "        hello world"


用法二:

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"


如果你需要移除字符串中的所有空白:

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


好吧,这是老问题了,但我自己也遇到过这个问题,除了删除所有空白之外,上面的答案都不起作用,这可能会损害应用的功能。我的问题是这样的:

["This", " is", " my", " array", " it is awesome"]

如果修剪所有的空白,这将是输出:

["This", "is", "my", "array", "itisawesome"]

所以我需要消除前导间距,并简单地从:

 let array = jsonData.components(separatedBy: ",")

let array = jsonData.components(separatedBy: ", ")

修正了这个问题。希望将来有人发现这个有用。

从技术上讲,这不是对原始问题的回答,但由于这里的许多帖子都给出了删除所有空白的答案,这里是一个更新的,更简洁的版本:

let stringWithouTAnyWhitespace = string.filter {!$0.isWhitespace}