我需要一种方法来从字符串中删除第一个字符,这是一个空格。我正在寻找一种方法,甚至是String类型的扩展,我可以用它来剪切一个字符串的字符。
答案 0 :(得分:329)
删除前导和尾随空格:
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces)
答案 1 :(得分:135)
当您想要删除所有类型的空格(基于this SO answer)时,正确的方法是:
extension String {
var stringByRemovingWhitespaces: String {
let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
return components.joinWithSeparator("")
}
}
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...])
}
}
答案 2 :(得分:76)
此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.
答案 3 :(得分:39)
Swift 3
您可以简单地使用此方法删除字符串中的所有普通空格(不考虑所有类型的空格):
let myString = " Hello World ! "
let formattedString = myString.replacingOccurrences(of: " ", with: "")
结果将是:
HelloWorld!
答案 4 :(得分:18)
您也可以使用正则表达式。
let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
答案 5 :(得分:16)
对于Swift 3.0+,请参阅其他答案。现在,这是Swift 2.x的遗留答案
如上所述,由于您有兴趣删除第一个字符, .stringByTrimmingCharactersInSet()实例方法将很好地工作:
myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
您还可以创建自己的字符集来修剪字符串的边界,例如:
myString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
还有一个内置实例方法来处理删除或替换名为 stringByReplacingOccurrencesOfString(target:String,replacement:String)的子字符串。它可以删除字符串中任何位置出现的空格或任何其他模式
您可以指定选项和范围,但不需要:
myString.stringByReplacingOccurrencesOfString(" ", withString: "")
这是一种简单的方法来删除或替换字符串中任何重复的字符模式,并且可以链接,但每次通过它都需要再次通过整个字符串,从而降低效率。所以你可以这样做:
myString.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString(",", withString: "")
......但需要两倍的时间。
.stringByReplacingOccurrencesOfString() documentation from Apple site
链接这些String实例方法有时可以非常方便地进行一次转换,例如,如果要将一个简短的NSData blob转换为一行中没有空格的十六进制字符串,可以使用Swift的内置字符串插值和一些修剪和更换:
("\(myNSDataBlob)").stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")).stringByReplacingOccurrencesOfString(" ", withString: "")
答案 6 :(得分:12)
swift 3.0
import Foundation
var str = " Hear me calling"
extension String {
var stringByRemovingWhitespaces: String {
return components(separatedBy: .whitespaces).joined()
}
}
str.stringByRemovingWhitespaces // Hearmecalling
答案 7 :(得分:7)
我会使用此扩展程序,以灵活模仿其他集合的方式:
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"
答案 8 :(得分:7)
使用正则表达式的绝佳案例:
" this is wrong contained teee xt "
.replacingOccurrences(of: "^\\s+|\\s+|\\s+$",
with: "",
options: .regularExpression)
// thisiswrongcontainedteeext
答案 9 :(得分:5)
如果您想要从正面(和背面)而不是中间删除空格,则应使用stringByTrimmingCharactersInSet
let dirtyString = " First Word "
let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
如果要从字符串中的任何位置删除空格,那么您可能需要查看stringByReplacing ...
答案 10 :(得分:3)
你也可以试试这个
let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")
答案 11 :(得分:3)
嗨,这可能很晚了,但值得尝试。这是来自游乐场文件。您可以将其设为String扩展名。
这是用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 "
答案 12 :(得分:3)
尝试使用函数式编程来删除空格:
extension String {
func whiteSpacesRemoved() -> String {
return self.filter { $0 != Character(" ") }
}
}
答案 13 :(得分:2)
extension String {
var removingWhitespaceAndNewLines: String {
return removing(.whitespacesAndNewlines)
}
func removing(_ forbiddenCharacters: CharacterSet) -> String {
return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
}
}
答案 14 :(得分:2)
快速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: "")
答案 15 :(得分:2)
let strFirstName = txtFirstName.text?.trimmingCharacters(in:
CharacterSet.whitespaces)
答案 16 :(得分:2)
如果有人从字符串中删除多余的空格,例如= "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."
答案 17 :(得分:2)
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)
}
答案 18 :(得分:1)
少写多做多。
"Hello World".filter({$0 != " "}) // HelloWorld
答案 19 :(得分:0)
对我来说,以下行用于删除空白。
let result = String(yourString.filter {![" ", "\t", "\n"].contains($0)})
答案 20 :(得分:0)
另一个答案,有时输入字符串在单词之间可以包含多个空格。如果您需要标准化以使单词之间只有1个空格,请尝试以下操作(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 !"
答案 21 :(得分:0)
string = string.filter ({!" ".contains($0) })
答案 22 :(得分:0)
对于任何寻求答案以从字符串中删除仅前导空格的人(正如问题标题明确要求的那样),这是一个答案:
假设:
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! "
我敢肯定还有比这更好的代码,但这对我有用。
答案 23 :(得分:0)
斯威夫特 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))
}
}
答案 24 :(得分:0)
用法:
let txt = " hello world "
let txt1 = txt.trimStart() // "hello world "
let txt2 = txt.trimEnd() // " hello world"
用法 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"
如果您需要从字符串中删除所有空格:
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)] }
}
答案 25 :(得分:-1)
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)
}
}
答案 26 :(得分:-1)
Swift 3版BadmintonCat的回答
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: "")
}
}
答案 27 :(得分:-2)
要删除字符串中的所有空格:
let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!