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


当前回答

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

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

其他回答

斯威夫特4

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

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

// thisiswrongcontainedteeext

这在swift 5中很管用

var myString = " Kwame Ch ef "
myString = myString.replacingOccurrences(of: " ", with: "")
print(myString)

output: Kwame Chef

你也可以试试这个

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

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 4修剪空白

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