0

how to remove special characters at the beginning/end of a string in swift 4

For example,

let myString = "abcde."

IF I want to remove special characters from the end of myString like . then it returns to me abcde

OR, if I want to remove e. at the end, it will return abcd.

AND, if I put something wrong like de, it will return the original string abcde.

Removing special characters at the beginning is the similar situation.

Kiran Sarvaiya
  • 1,318
  • 1
  • 13
  • 37
Braver Chiang
  • 351
  • 2
  • 13

1 Answers1

0

The only thing you should do to meet the requirement in the question is to make an extension of String

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
Braver Chiang
  • 351
  • 2
  • 13