! !! yuahl! !
之类的字符串,我希望删除!
和,当我像这样编码时
for index in InputName.characters.indices {
if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
InputName.removeAtIndex(index)
}
}
有这个错误“致命错误:下标:subRange扩展超过String结束”,我该怎么办? THX:D
答案 0 :(得分:8)
Swift 3 +
let myString = "aaaaaaaabbbb"
let replaced = myString.replacingOccurrences(of: "bbbb", with: "") // "aaaaaaaa"
答案 1 :(得分:4)
我发现filter
方法是一种很好的方法:
let unfiltered = "! !! yuahl! !"
// Array of Characters to remove
let removal: [Character] = ["!"," "]
// turn the string into an Array
let unfilteredCharacters = unfiltered.characters
// return an Array without the removal Characters
let filteredCharacters = unfilteredCharacters.filter { !removal.contains($0) }
// build a String with the filtered Array
let filtered = String(filteredCharacters)
print(filtered) // => "yeah"
// combined to a single line
print(String(unfiltered.characters.filter { !removal.contains($0) })) // => "yuahl"
答案 2 :(得分:3)
如果您只需要删除两端的字符,可以使用stringByTrimmingCharactersInSet(_:)
let delCharSet = NSCharacterSet(charactersInString: "! ")
let s1 = "! aString! !"
let s1Del = s1.stringByTrimmingCharactersInSet(delCharSet)
print(s1Del) //->aString
let s2 = "! anotherString !! aString! !"
let s2Del = s2.stringByTrimmingCharactersInSet(delCharSet)
print(s2Del) //->anotherString !! aString
如果您还需要在中间删除字符,请从过滤后的输出中重建"比重复单个字符删除更有效率。
var tempUSView = String.UnicodeScalarView()
tempUSView.appendContentsOf(s2.unicodeScalars.lazy.filter{!delCharSet.longCharacterIsMember($0.value)})
let s2DelAll = String(tempUSView)
print(s2DelAll) //->anotherStringaString
如果您不介意生成许多中间字符串和数组,这个单线程可以生成预期的输出:
let s2DelAll2 = s2.componentsSeparatedByCharactersInSet(delCharSet).joinWithSeparator("")
print(s2DelAll2) //->anotherStringaString
答案 3 :(得分:2)
Swift 3
在Swift 3中,语法更好一些。由于旧API的Great Swiftification,工厂方法现在称为trimmingCharacters(in:)
。此外,您可以将CharacterSet
构建为单个字符Set
的{{1}}:
String
如果您要删除字符串中间的字符,则可以使用let string = "! !! yuahl! !"
string.trimmingCharacters(in: [" ", "!"]) // "yuahl"
:
components(separatedBy:).joined()
Swift 2版本的H / T @OOPer
答案 4 :(得分:2)
func trimLast(character chars: Set<Character>) -> String { let str: String = String(self.reversed()) guard let index = str.index(where: {!chars.contains($0)}) else { return self } return String((str[index..<str.endIndex]).reversed()) }
注意:
通过在String
扩展名中添加此功能,您可以最后删除字符串的特定字符。
答案 5 :(得分:0)
for index in InputName.characters.indices.reversed() {
if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
InputName.removeAtIndex(index)
}
}
答案 6 :(得分:0)
您还可以添加这样非常有用的扩展程序:
import Foundation
extension String{
func exclude(find:String) -> String {
return stringByReplacingOccurrencesOfString(find, withString: "", options: .CaseInsensitiveSearch, range: nil)
}
func replaceAll(find:String, with:String) -> String {
return stringByReplacingOccurrencesOfString(find, withString: with, options: .CaseInsensitiveSearch, range: nil)
}
}