简体   繁体   English

如何在Swift 4中删除字符串开头/结尾(第一个/最后一个)的特殊字符

[英]how to remove special characters at the beginning / end (first/last) of a string in swift 4

how to remove special characters at the beginning/end of a string in swift 4 如何在Swift 4中删除字符串开头/结尾的特殊字符

For example, 例如,

let myString = "abcde."

IF I want to remove special characters from the end of myString like . 如果我想从myString末尾删除特殊字符,例如. then it returns to me abcde 后返回给我abcde

OR , if I want to remove e. 或者 ,如果我要删除e. at the end, it will return abcd . 最后,它将返回abcd

AND , if I put something wrong like de , it will return the original string abcde. AND ,如果我输入了诸如de错误信息,它将返回原始字符串abcde.

Removing special characters at the beginning is the similar situation. 开始删除特殊字符的情况与此类似。

The only thing you should do to meet the requirement in the question is to make an extension of String 要满足问题中的要求,您唯一要做的就是对String进行extension

extension String {
    // remove the end
    func removeTheSpecialCharAtLast(char: String) -> String {
        if hasSuffix(char){
            return String(dropLast(char.count))
        }
        return self
    }

    // remove the beginning
    func removeTheSpecialCharAtFirst(char: String) -> String {
        if hasPrefix(char){
            return String(dropFirst(char.count))
        }
        return self
    }
}

And, I've made a test to remove chars at the end. 而且,我已经进行了测试以最后删除字符。 To remove chars at the beginning is similar 在一开始删除字符是相似的

    let myString = "abcde."
    let op1 = myString.removeTheSpecialCharAtLast(char: "cd")
    let op2 = myString.removeTheSpecialCharAtLast(char: ".")
    let op3 = myString.removeTheSpecialCharAtLast(char: "de")
    let op4 = myString.removeTheSpecialCharAtLast(char: "de.")
    print(op1)   //abcde.
    print(op2)   //abcde
    print(op3)   //abcde.
    print(op4)   //abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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