How to Remove the Last Character from a String in Swift?

Removing last character from string

Like for example if there is one string “Here is an apple?” and you want that last character of string is not required for you or it is necessary to remove / eliminate that character then this case occurs where last character is removed from string.

How to remove the last character from string in swift?

Way 1:
extension String {
func removeLastCharacter() {
return self.substring(from: 0, to: self.count-2)
}
}

Use in code :

let string : String = "Please remove last character@"
string = string.removeLastCharacter()
print("New String ==> \(str)")

OUTPUT :- “New String ==> Please remove last character”

Way 2:
extension UIViewController {
func removeLastCharacter(str : String) {
str = str.substring(from: 0, to: str.count-2)
}
}

Use in code :
let string : String = "Please remove last character@"
string = self.removeLastCharacter(str : string)
print("New String ==> \(string)")

OUTPUT :- “New String ==> Please remove last character”

Leave a Comment