swiftnscharacterset

Remove last punctuation of a swift string


I'm trying to remove the last punctuation of a string in swift 2.0

var str: String = "This is a string, but i need to remove this comma,      \n"
var trimmedstr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

First I'm removing the the white spaces and newline characters at the end, and then I need to check of the last character of trimmedstr if it is a punctuation. It can be a period, comma, dash, etc, and if it is i need to remove it it.

How can i accomplish this?


Solution

  • There are multiple ways to do it. You can use contains to check if the last character is in the set of expected characters, and use dropLast() on the String to construct a new string without the last character:

    let str = "This is a string, but i need to remove this comma, \n"
    
    let trimmedstr = str.trimmingCharacters(in: .whitespacesAndNewlines)
    
    if let lastchar = trimmedstr.last {
        if [",", ".", "-", "?"].contains(lastchar) {
            let newstr = String(trimmedstr.dropLast())
            print(newstr)
        }
    }