swift2 斯威夫特:我怎样才能删除一个特定字符?

vwoqyblh  于 2022-11-06  发布在  Swift
关注(0)|答案(8)|浏览(195)

一个字符串,比如! !! yuahl! !,我想删除!和``,当我这样编写代码时

for index in InputName.characters.indices {
    if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
        InputName.removeAtIndex(index)
    }
}

出现以下错误“致命错误:subscript:subRange扩展到字符串末尾“之后,应该怎么做?

brqmpdu1

brqmpdu11#

雨燕5+

let myString = "aaaaaaaabbbb"
let replaced = myString.replacingOccurrences(of: "bbbb", with: "") // "aaaaaaaa"
4urapxun

4urapxun2#

如果只需要删除两端的字符,则可以使用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

如果您不介意生成许多中间的String和Array,那么这个单独的liner可以生成预期的输出:

let s2DelAll2 = s2.componentsSeparatedByCharactersInSet(delCharSet).joinWithSeparator("")
print(s2DelAll2) //->anotherStringaString
voj3qocg

voj3qocg3#

我发现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"
f0ofjuux

f0ofjuux4#

雨燕3

在Swift 3中,语法更好一些。由于旧API的Great Swifification,工厂方法现在被称为trimmingCharacters(in:)。同样,你可以将CharacterSet构造为单字符String s的Set

let string = "!   !! yuahl! !"
string.trimmingCharacters(in: [" ", "!"]) // "yuahl"

如果字符串中间也有要删除的字符,则可以使用components(separatedBy:).joined()

let string = "!   !! yu !ahl! !"
string.components(separatedBy: ["!", " "]).joined() // "yuahl"

Swift 2版本的H/T @OOPer

mwngjboj

mwngjboj5#

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扩展中增加此函数,最终可以删除字符串中的特定字符。

bfhwhh0e

bfhwhh0e6#

for index in InputName.characters.indices.reversed() {
    if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
        InputName.removeAtIndex(index)
    }
}
6jygbczu

6jygbczu7#

你也可以添加这样非常有帮助的扩展:

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

n1bvdmb68#

您可以使用以下命令:
例如,如果要从10%中删除百分比“%”

if let i = text.firstIndex(of: "%") {
        text.remove(at: i) //10
    }

相关问题