简体   繁体   中英

How to replace multiple characters in swift

Hi guys I have a problem with replacingOccurences, couldn't get more than one character. I tried this code but it didn't work. When i enter the this text = "aaba kouq bux" if repTime[c] = 2 I want to delete a,b,u, then get this text = "koq x"

func removeString(text:String, repTime : Int)-> String{
    
 var repTime = [Character: Int]()

 for c in text {
    
     if let count = repTime[c] {
         repTime[c] = count + 1
     } else {
         repTime[c] = 1
     }
    
    if repTime[c] == 2{
    let textA = text.replacingOccurrences(of: "[ a|\\b|\\u]", with: "",options: [.regularExpression])
    return textA
    }
 }
return text
}

Using replacingOccurrences means that you would like to replace occurrences of string within string. So basically you would use it to replace all occurrences of "dog" with "cat". It means that "I have a dog. My dog is very neat..." would be converted to "I have a cat. My cat is very neat...".

From what your seem to try to do is to actually filter out some of the characters. You could try an answer like this one . With some small tweaks you should probably get something like

let textA = text.filter { "[ a|\\b|\\u]".contains($0) == false }

So basically you would like to have a same text but removing all characters that are contained within the string "[ a|\\b|\\u]" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM